ceulen 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +72 -0
- package/extensions/lib/registry.ts +16 -3
- 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/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/index.ts +3 -0
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/gh/configPanel.ts +82 -0
- package/extensions/modules/gh/index.ts +86 -0
- package/extensions/modules/gh/lib/gh-cli.ts +337 -0
- package/extensions/modules/gh/lib/ops.ts +771 -0
- package/extensions/modules/gh/test/gh.test.ts +280 -0
- package/extensions/modules/plan/lib/plan-tools.ts +8 -0
- package/extensions/modules/repair/index.ts +138 -0
- package/extensions/modules/repair/lib/guards.ts +1 -1
- package/extensions/modules/repair/lib/read-selector.ts +242 -0
- package/extensions/modules/repair/test/read-selector.test.ts +198 -0
- package/extensions/modules/steering/configPanel.ts +8 -0
- package/extensions/modules/steering/index.ts +6 -0
- package/extensions/modules/steering/lib/settings.ts +6 -2
- package/extensions/modules/steering/lib/think.ts +66 -0
- package/extensions/modules/steering/test/harness.ts +5 -0
- package/extensions/modules/steering/test/settings.test.ts +2 -0
- package/extensions/modules/steering/test/think.test.ts +77 -0
- package/extensions/modules/todo/configPanel.ts +55 -0
- package/extensions/modules/todo/index.ts +46 -13
- 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 +276 -0
- package/extensions/modules/web/index.ts +37 -1
- package/extensions/modules/web/lib/a11y.ts +252 -0
- package/extensions/modules/web/test/a11y.test.ts +218 -0
- package/extensions/modules/web/test/extension.test.ts +2 -2
- package/extensions/modules/web/test/hook.test.ts +2 -2
- package/extensions/modules/web/vendor/axe/LICENSE +362 -0
- package/extensions/modules/web/vendor/axe/LICENSE-3RD-PARTY.txt +66 -0
- package/extensions/modules/web/vendor/axe/README.md +19 -0
- package/extensions/modules/web/vendor/axe/axe.min.js +12 -0
- package/package.json +2 -2
- package/skills/a2a/SKILL.md +63 -0
- package/skills/web/SKILL.md +1 -0
|
@@ -0,0 +1,1436 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A2A inbound server — exposes Pi as an A2A-discoverable agent.
|
|
3
|
+
*
|
|
4
|
+
* Pi has no platform-adapter API (unlike Hermes' ctx.register_platform), so
|
|
5
|
+
* inbound tasks each spawn an ISOLATED agent session via createAgentSession()
|
|
6
|
+
* (the same proven path pi-subagent uses), run to completion, capture the
|
|
7
|
+
* reply, and return it as the task result. This is "an agent invocation in
|
|
8
|
+
* your repo", not "the live TUI session" — the correct, honest boundary for a
|
|
9
|
+
* coding agent.
|
|
10
|
+
*
|
|
11
|
+
* Transport: node:http (stdlib). Security: localhost-default bind, token-gated
|
|
12
|
+
* remote, outbound redaction, inbound injection filtering, audit log, anti-loop.
|
|
13
|
+
*
|
|
14
|
+
* Enabled only when `a2a.server.enabled` is true (default false).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
|
|
18
|
+
import { hostname } from "node:os";
|
|
19
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
20
|
+
import {
|
|
21
|
+
PROTOCOL_VERSION,
|
|
22
|
+
PI_SESSION_EXTENSION_URI,
|
|
23
|
+
STATE_CANCELED,
|
|
24
|
+
STATE_COMPLETED,
|
|
25
|
+
STATE_FAILED,
|
|
26
|
+
STATE_INPUT_REQUIRED,
|
|
27
|
+
STATE_REJECTED,
|
|
28
|
+
STATE_WORKING,
|
|
29
|
+
buildAgentCard,
|
|
30
|
+
buildTask,
|
|
31
|
+
extractText,
|
|
32
|
+
artifactUpdateEvent,
|
|
33
|
+
jsonrpcError,
|
|
34
|
+
jsonrpcResult,
|
|
35
|
+
newContextId,
|
|
36
|
+
newTaskId,
|
|
37
|
+
normalizeRole,
|
|
38
|
+
sendTaskResponse,
|
|
39
|
+
statusUpdateEvent,
|
|
40
|
+
TERMINAL_STATES,
|
|
41
|
+
uuid,
|
|
42
|
+
type AgentCard,
|
|
43
|
+
type AgentSkill,
|
|
44
|
+
type Message,
|
|
45
|
+
type Task,
|
|
46
|
+
} from "./protocol";
|
|
47
|
+
import type { A2AConfig } from "./config";
|
|
48
|
+
import { setGatewayRegistrationName, updateGatewayPeers, cleanHostName } from "./config";
|
|
49
|
+
import {
|
|
50
|
+
AntiLoop,
|
|
51
|
+
audit,
|
|
52
|
+
authenticateInfo,
|
|
53
|
+
IDENTITY_HEADER,
|
|
54
|
+
isTrustedPeer,
|
|
55
|
+
LOOPBACK,
|
|
56
|
+
localhostOnly,
|
|
57
|
+
maxPingpongTurns,
|
|
58
|
+
redactOutbound,
|
|
59
|
+
resolveBindHost,
|
|
60
|
+
transportName,
|
|
61
|
+
wrapInbound,
|
|
62
|
+
type InboundFraming,
|
|
63
|
+
} from "./security";
|
|
64
|
+
import { metrics } from "./client";
|
|
65
|
+
import { childTranscriptDir, sweepChildTranscripts } from "./persistence";
|
|
66
|
+
import { heartbeat, register, unregister, type SessionDescriptor } from "./registry";
|
|
67
|
+
import { startBroadcast, startDiscovery, txtRecord, mdnsPeerKey, type MdnsHandle, type MdnsPeer } from "./mdns";
|
|
68
|
+
import type { InboundActivity } from "./activity";
|
|
69
|
+
import { preview } from "./activity";
|
|
70
|
+
|
|
71
|
+
// ---------------------------------------------------------------------------
|
|
72
|
+
// Task store (in-memory, bounded — evicts DONE tasks only, never running ones)
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
|
|
75
|
+
const MAX_TASKS = 500;
|
|
76
|
+
|
|
77
|
+
interface StoredTask {
|
|
78
|
+
task: Task;
|
|
79
|
+
controller?: AbortController;
|
|
80
|
+
done: boolean;
|
|
81
|
+
/** Set by tasks/cancel so the catch path classifies it as CANCELED, not timeout-FAILED. */
|
|
82
|
+
userCanceled?: boolean;
|
|
83
|
+
/** Owning authenticated identity (per-identity ownership, #10). */
|
|
84
|
+
identity: string;
|
|
85
|
+
subscribeWatchers: Array<(t: Task) => void>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
class TaskStore {
|
|
89
|
+
private tasks = new Map<string, StoredTask>();
|
|
90
|
+
private order: string[] = [];
|
|
91
|
+
|
|
92
|
+
get(id: string): StoredTask | undefined {
|
|
93
|
+
return this.tasks.get(id);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
add(id: string, st: StoredTask): void {
|
|
97
|
+
this.tasks.set(id, st);
|
|
98
|
+
this.order.push(id);
|
|
99
|
+
// Evict oldest DONE tasks only. A running task (done=false) must never be
|
|
100
|
+
// evicted or store.get(id)! would throw mid-execution. Guard against an
|
|
101
|
+
// all-running pathological case with a hard cap.
|
|
102
|
+
let guard = 0;
|
|
103
|
+
while (this.order.length > MAX_TASKS && guard++ < MAX_TASKS * 2) {
|
|
104
|
+
const old = this.order[0]!;
|
|
105
|
+
const candidate = this.tasks.get(old);
|
|
106
|
+
if (candidate && !candidate.done) {
|
|
107
|
+
// Running — move to the back so it isn't re-examined every iteration.
|
|
108
|
+
this.order.push(this.order.shift()!);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
this.order.shift();
|
|
112
|
+
this.tasks.delete(old);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
list(): Task[] {
|
|
117
|
+
return this.order.map((id) => this.tasks.get(id)?.task).filter((t): t is Task => !!t);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
update(id: string, patch: (t: Task) => void): StoredTask | undefined {
|
|
121
|
+
const st = this.tasks.get(id);
|
|
122
|
+
if (!st) return undefined;
|
|
123
|
+
patch(st.task);
|
|
124
|
+
st.task.status.timestamp = new Date().toISOString();
|
|
125
|
+
for (const w of st.subscribeWatchers) {
|
|
126
|
+
try {
|
|
127
|
+
w(st.task);
|
|
128
|
+
} catch {
|
|
129
|
+
/* watcher best-effort */
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return st;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// ---------------------------------------------------------------------------
|
|
137
|
+
// Non-blocking send detection (A2A v1.0 §3.2.2 SendMessageConfiguration)
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
/** True when the caller asked for an immediate in-progress Task ack instead
|
|
141
|
+
* of waiting for the terminal state (submit-and-poll). Accepts the
|
|
142
|
+
* snake_case spelling some early clients send. */
|
|
143
|
+
function wantsImmediateReturn(params: any): boolean {
|
|
144
|
+
const cfg = params?.configuration;
|
|
145
|
+
if (!cfg || typeof cfg !== "object") return false;
|
|
146
|
+
return cfg.returnImmediately === true || cfg.return_immediately === true;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// ---------------------------------------------------------------------------
|
|
150
|
+
// Rate limiter (sliding window per identity; prunes stale entries)
|
|
151
|
+
// ---------------------------------------------------------------------------
|
|
152
|
+
|
|
153
|
+
class RateLimiter {
|
|
154
|
+
private hits = new Map<string, number[]>();
|
|
155
|
+
private sweepCounter = 0;
|
|
156
|
+
private readonly sweepEvery = 64; // periodic prune of stale keys
|
|
157
|
+
private readonly maxKeys = 10000;
|
|
158
|
+
constructor(private perMin: number) {}
|
|
159
|
+
|
|
160
|
+
check(identity: string): boolean {
|
|
161
|
+
const now = Date.now();
|
|
162
|
+
const win = (this.hits.get(identity) ?? []).filter((t) => now - t < 60000);
|
|
163
|
+
if (win.length === 0) {
|
|
164
|
+
this.hits.delete(identity);
|
|
165
|
+
} else {
|
|
166
|
+
this.hits.set(identity, win);
|
|
167
|
+
}
|
|
168
|
+
// Periodic sweep of stale entries so one-off identities don't accumulate.
|
|
169
|
+
if (++this.sweepCounter >= this.sweepEvery) {
|
|
170
|
+
this.sweepCounter = 0;
|
|
171
|
+
for (const [k, v] of this.hits) {
|
|
172
|
+
if (v.every((t) => now - t >= 60000)) this.hits.delete(k);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
// Hard cap to bound memory under adversarial unique-identity flooding.
|
|
176
|
+
if (this.hits.size > this.maxKeys) {
|
|
177
|
+
const firstKey = this.hits.keys().next().value;
|
|
178
|
+
if (firstKey) this.hits.delete(firstKey);
|
|
179
|
+
}
|
|
180
|
+
if (win.length >= this.perMin) return false;
|
|
181
|
+
win.push(now);
|
|
182
|
+
this.hits.set(identity, win);
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ---------------------------------------------------------------------------
|
|
188
|
+
// Session runner — the injectable boundary for testing
|
|
189
|
+
// ---------------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Contract: a normal return asserts the turn finished (or needs input) —
|
|
193
|
+
* in particular, that the final assistant message carried usable text. A
|
|
194
|
+
* turn that ends on a length stop with no assistant text produced no usable
|
|
195
|
+
* reply and MUST throw, so messageSend maps the task to FAILED instead of
|
|
196
|
+
* completing it with the previous turn's stale text. If the abort signal
|
|
197
|
+
* fired first, the runner MUST likewise throw — messageSend routes any
|
|
198
|
+
* normal return after an abort through the failure classification anyway,
|
|
199
|
+
* and an honest throw carries the real error (timeout vs cancel).
|
|
200
|
+
*/
|
|
201
|
+
export interface SessionRunner {
|
|
202
|
+
(opts: {
|
|
203
|
+
message: string;
|
|
204
|
+
/** A2A task id of this dispatch — the runner keys the persisted child
|
|
205
|
+
* session transcript by it (fleet task #252). Absent in tests. */
|
|
206
|
+
taskId?: string;
|
|
207
|
+
signal: AbortSignal;
|
|
208
|
+
onProgress?: (assistantTextDelta: string) => void;
|
|
209
|
+
}): Promise<{
|
|
210
|
+
reply: string;
|
|
211
|
+
inputRequired: boolean;
|
|
212
|
+
/** Path of the persisted child transcript, when the runner wrote one
|
|
213
|
+
* (fleet task #252). Audited at completion AND failure so a dead
|
|
214
|
+
* worker's step history is discoverable from the audit log alone. */
|
|
215
|
+
transcriptPath?: string;
|
|
216
|
+
/** Assistant turns + tool executions the runner observed — with the
|
|
217
|
+
* transcript, answers "how far did it get" in a post-mortem (#256). */
|
|
218
|
+
stepCount?: number;
|
|
219
|
+
}>;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ---------------------------------------------------------------------------
|
|
223
|
+
// A2A server
|
|
224
|
+
// ---------------------------------------------------------------------------
|
|
225
|
+
|
|
226
|
+
export class A2AServer {
|
|
227
|
+
private http: Server | null = null;
|
|
228
|
+
private boundPort: number | null = null;
|
|
229
|
+
/** True once the listening socket bound a loopback host — the gate for
|
|
230
|
+
* honoring X-A2A-Identity asserted names (fleet task #322). Defaults
|
|
231
|
+
* false: until the server knows it bound loopback, no header trust. */
|
|
232
|
+
private loopbackBind = false;
|
|
233
|
+
private store = new TaskStore();
|
|
234
|
+
/** Per-session minted inbound tokens (peer name → agw-* token) registered
|
|
235
|
+
* as upstream_token with gateways. Kept OUT of cfg.server.peerTokens. */
|
|
236
|
+
private mintedInboundTokens: Record<string, string> = {};
|
|
237
|
+
private antiLoop: AntiLoop;
|
|
238
|
+
private limiter: RateLimiter;
|
|
239
|
+
private cfg: A2AConfig;
|
|
240
|
+
private ctx: ExtensionContext | undefined;
|
|
241
|
+
private cwd: string;
|
|
242
|
+
private piDir: string;
|
|
243
|
+
private runner: SessionRunner | undefined;
|
|
244
|
+
// Two admission pools, both sized cfg.server.maxConcurrent: `running`
|
|
245
|
+
// counts blocking message/send + message/stream tasks, `detachedRunning`
|
|
246
|
+
// counts detached (returnImmediately) runs. Detached tasks hold their slot
|
|
247
|
+
// up to asyncTimeoutSec (default 24h) — a shared counter let 3 hung
|
|
248
|
+
// detached dispatches 503 ALL blocking senders (self-inflicted outage).
|
|
249
|
+
private running = 0;
|
|
250
|
+
private detachedRunning = 0;
|
|
251
|
+
// Discovery state (0.2.0)
|
|
252
|
+
private descriptor: SessionDescriptor | null = null;
|
|
253
|
+
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
|
254
|
+
private mdnsBroadcast: MdnsHandle | null = null;
|
|
255
|
+
private mdnsDiscovery: MdnsHandle | null = null;
|
|
256
|
+
private mdnsPeers: MdnsPeer[] = [];
|
|
257
|
+
/** One GatewayUpstream per configured gateway (0.6.0), keyed by gateway key. */
|
|
258
|
+
private gatewayUpstreams = new Map<string, import("./gateway.js").GatewayUpstream>();
|
|
259
|
+
private pid = process.pid;
|
|
260
|
+
/** Mirrors the SDK's SlashCommandSource union so a rename upstream breaks
|
|
261
|
+
* typecheck instead of silently disabling skill discovery. */
|
|
262
|
+
private api:
|
|
263
|
+
| {
|
|
264
|
+
getActiveTools?: () => string[];
|
|
265
|
+
getCommands?: () => Array<{
|
|
266
|
+
name: string;
|
|
267
|
+
description?: string;
|
|
268
|
+
source: "extension" | "prompt" | "skill";
|
|
269
|
+
}>;
|
|
270
|
+
}
|
|
271
|
+
| undefined;
|
|
272
|
+
/** Host-TUI activity hook (0.3.0) — fired on task lifecycle events. */
|
|
273
|
+
private onActivity: ((a: InboundActivity) => void) | undefined;
|
|
274
|
+
/** Host-TUI status hook — gateway registration result (replaces console.log). */
|
|
275
|
+
private onStatus: ((msg: string) => void) | undefined;
|
|
276
|
+
/** Gateway diagnostic hook — upstream/channel failures (replaces console.error). */
|
|
277
|
+
private onError: ((msg: string) => void) | undefined;
|
|
278
|
+
|
|
279
|
+
constructor(opts: {
|
|
280
|
+
cfg: A2AConfig;
|
|
281
|
+
ctx?: ExtensionContext;
|
|
282
|
+
cwd: string;
|
|
283
|
+
piDir: string;
|
|
284
|
+
runner?: SessionRunner;
|
|
285
|
+
api?: {
|
|
286
|
+
getActiveTools?: () => string[];
|
|
287
|
+
getCommands?: () => Array<{
|
|
288
|
+
name: string;
|
|
289
|
+
description?: string;
|
|
290
|
+
source: "extension" | "prompt" | "skill";
|
|
291
|
+
}>;
|
|
292
|
+
};
|
|
293
|
+
onActivity?: (a: InboundActivity) => void;
|
|
294
|
+
/** Called with human-readable status lines (gateway registration) so the
|
|
295
|
+
* host can surface them as a TUI toast instead of console.log. */
|
|
296
|
+
onStatus?: (msg: string) => void;
|
|
297
|
+
/** Gateway diagnostic lines (register failed, channel dropped, …) — kept
|
|
298
|
+
* OFF the status surface so they never interleave with lifecycle lines. */
|
|
299
|
+
onError?: (msg: string) => void;
|
|
300
|
+
}) {
|
|
301
|
+
this.cfg = opts.cfg;
|
|
302
|
+
this.ctx = opts.ctx;
|
|
303
|
+
this.api = opts.api;
|
|
304
|
+
this.onActivity = opts.onActivity;
|
|
305
|
+
this.onStatus = opts.onStatus;
|
|
306
|
+
this.onError = opts.onError ?? console.error;
|
|
307
|
+
this.cwd = opts.cwd;
|
|
308
|
+
this.piDir = opts.piDir;
|
|
309
|
+
this.runner = opts.runner;
|
|
310
|
+
this.antiLoop = new AntiLoop(maxPingpongTurns(opts.cfg));
|
|
311
|
+
this.limiter = new RateLimiter(opts.cfg.server.rateLimitPerMin);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
setRunner(runner: SessionRunner): void {
|
|
315
|
+
this.runner = runner;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Public URL the Agent Card advertises. Uses the ACTUAL bound port after
|
|
319
|
+
* fallback (critical — advertising a configured-but-unbound port breaks
|
|
320
|
+
* peers' callbacks). */
|
|
321
|
+
private publicUrl(): string {
|
|
322
|
+
const explicit = this.cfg.server.publicUrl.trim();
|
|
323
|
+
if (explicit) return explicit.replace(/\/+$/, "") + "/";
|
|
324
|
+
const host = resolveBindHost(this.cfg);
|
|
325
|
+
const port = this.boundPort ?? this.cfg.server.port;
|
|
326
|
+
return `http://${host}:${port}/`;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
private buildCard(stripEnrichedMetadata = false): AgentCard {
|
|
330
|
+
const url = this.publicUrl();
|
|
331
|
+
const name = this.sessionName();
|
|
332
|
+
return buildAgentCard({
|
|
333
|
+
name,
|
|
334
|
+
url,
|
|
335
|
+
description: "Pi coding agent — A2A-callable. Runs in the configured workspace.",
|
|
336
|
+
skills: this.activeSkills(stripEnrichedMetadata),
|
|
337
|
+
streaming: true,
|
|
338
|
+
pushNotifications: false,
|
|
339
|
+
authRequired: !localhostOnly(this.cfg),
|
|
340
|
+
sessionMetadata: !stripEnrichedMetadata && this.cfg.discovery.enrichCard && this.descriptor
|
|
341
|
+
? this.cardMetadata()
|
|
342
|
+
: undefined,
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Display name: the pinned agentName wins; the unpinned default gets the
|
|
347
|
+
* bound port suffixed (hostname-9912) so same-machine sessions don't all
|
|
348
|
+
* collide on one registry/discovery name. Mirrors the gateway name
|
|
349
|
+
* convention (`<base>-<port>`). `.local`/`.LAN` mDNS suffixes stripped for
|
|
350
|
+
* cleaner names (MBP-Sao.local → mbp-sao). */
|
|
351
|
+
private baseName(): string {
|
|
352
|
+
return cleanHostName(hostname());
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
private sessionName(): string {
|
|
356
|
+
return this.cfg.server.agentName || `${this.baseName()}-${this.boundPort ?? this.cfg.server.port}`;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Build the A2A-Extensions metadata map from the live session descriptor. */
|
|
360
|
+
private cardMetadata(): Record<string, unknown> {
|
|
361
|
+
const d = this.descriptor!;
|
|
362
|
+
return {
|
|
363
|
+
pid: d.pid,
|
|
364
|
+
cwd: d.cwd,
|
|
365
|
+
model: d.model,
|
|
366
|
+
tools: d.tools,
|
|
367
|
+
sessionName: d.sessionName,
|
|
368
|
+
sessionId: d.sessionId,
|
|
369
|
+
selfIdentity: d.selfIdentity,
|
|
370
|
+
agentName: d.agentName,
|
|
371
|
+
startedAt: d.startedAt,
|
|
372
|
+
// Extension URI echoed in metadata for peers that read metadata before capabilities.
|
|
373
|
+
extension: PI_SESSION_EXTENSION_URI,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Snapshot the current session identity (cwd/model/tools) into a descriptor. */
|
|
378
|
+
/** Snapshot the current session identity (cwd/model/tools) into a descriptor. */
|
|
379
|
+
private buildDescriptor(): SessionDescriptor {
|
|
380
|
+
const m = this.ctx?.model as any;
|
|
381
|
+
const model = m
|
|
382
|
+
? { provider: String(m.provider ?? ""), id: String(m.id ?? ""), name: m.name ? String(m.name) : undefined }
|
|
383
|
+
: null;
|
|
384
|
+
return {
|
|
385
|
+
pid: this.pid,
|
|
386
|
+
url: this.publicUrl(),
|
|
387
|
+
port: this.boundPort ?? this.cfg.server.port,
|
|
388
|
+
host: resolveBindHost(this.cfg),
|
|
389
|
+
cwd: this.cwd,
|
|
390
|
+
model,
|
|
391
|
+
agentName: this.sessionName(),
|
|
392
|
+
sessionName: this.ctx ? (this.ctx as any).getSessionName?.() : undefined,
|
|
393
|
+
sessionId: this.ctx ? (this.ctx as any).sessionManager?.getSessionId?.() : undefined,
|
|
394
|
+
selfIdentity: this.cfg.selfIdentity || undefined,
|
|
395
|
+
tools: this.activeTools(),
|
|
396
|
+
skills: this.activeSkills(),
|
|
397
|
+
startedAt: this.descriptor?.startedAt ?? new Date().toISOString(),
|
|
398
|
+
mtime: Date.now(),
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Best-effort active-tools snapshot (ctx may not expose getActiveTools in all modes). */
|
|
403
|
+
private activeTools(): string[] {
|
|
404
|
+
try {
|
|
405
|
+
if (this.api && typeof this.api.getActiveTools === "function") return this.api.getActiveTools();
|
|
406
|
+
} catch {
|
|
407
|
+
/* ignore */
|
|
408
|
+
}
|
|
409
|
+
return [];
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Self-discovered skills from the live session: getCommands() lists every
|
|
413
|
+
* loaded skill as `skill:<name>` (source "skill") straight from the resource
|
|
414
|
+
* loader (user + project + extension-package skills). Explicit
|
|
415
|
+
* cfg.server.skills still wins (backward compat). When `anonymous` is set,
|
|
416
|
+
* discovered skills are withheld (they disclose local SKILL.md content to
|
|
417
|
+
* unauthenticated callers) — explicitly configured skills stay public, as
|
|
418
|
+
* they were pre-0.6.3 opt-in. */
|
|
419
|
+
private activeSkills(anonymous = false): AgentSkill[] {
|
|
420
|
+
if (this.cfg.server.skills.length) return this.cfg.server.skills;
|
|
421
|
+
const FALLBACK: AgentSkill[] = [
|
|
422
|
+
{ id: "coding", name: "coding", description: "Read, edit, run, debug, refactor, test" },
|
|
423
|
+
];
|
|
424
|
+
if (anonymous) return FALLBACK;
|
|
425
|
+
try {
|
|
426
|
+
const cmds = this.api?.getCommands?.() ?? [];
|
|
427
|
+
const skills = cmds
|
|
428
|
+
.filter((c) => c.source === "skill" && c.name.startsWith("skill:"))
|
|
429
|
+
.map((c) => ({
|
|
430
|
+
id: c.name.slice("skill:".length),
|
|
431
|
+
name: c.name.slice("skill:".length),
|
|
432
|
+
description: (c.description ?? "").slice(0, 1024),
|
|
433
|
+
}));
|
|
434
|
+
return skills.length ? skills : FALLBACK;
|
|
435
|
+
} catch {
|
|
436
|
+
return FALLBACK;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** Re-snapshot cwd/model/tools and refresh the registry + card (call on model_select). */
|
|
441
|
+
refreshDescriptor(): void {
|
|
442
|
+
if (!this.descriptor || !this.cfg.discovery.local.enabled) return;
|
|
443
|
+
this.descriptor = this.buildDescriptor();
|
|
444
|
+
heartbeat(this.descriptor, this.piDir);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Read-only access to discovered mDNS peers (for a2a_peers). */
|
|
448
|
+
get discoveredMdnsPeers(): MdnsPeer[] {
|
|
449
|
+
return this.mdnsPeers;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Start local-registry declaration + optional mDNS broadcast/discovery. */
|
|
453
|
+
private async startDiscovery(): Promise<void> {
|
|
454
|
+
// Build the descriptor unconditionally — it's needed for both local and mDNS.
|
|
455
|
+
this.descriptor = this.buildDescriptor();
|
|
456
|
+
|
|
457
|
+
// Layer 1: local file registry (opt-out).
|
|
458
|
+
if (this.cfg.discovery.local.enabled) {
|
|
459
|
+
register(this.descriptor, this.piDir);
|
|
460
|
+
const intervalMs = Math.max(1, this.cfg.discovery.local.heartbeatSec) * 1000;
|
|
461
|
+
this.heartbeatTimer = setInterval(() => {
|
|
462
|
+
if (this.descriptor) heartbeat(this.descriptor, this.piDir);
|
|
463
|
+
}, intervalMs);
|
|
464
|
+
this.heartbeatTimer.unref?.(); // don't keep the process alive on exit
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Layer 3: mDNS broadcast + discovery (independent of local registry).
|
|
468
|
+
if (this.cfg.discovery.mdns.enabled && this.descriptor) {
|
|
469
|
+
const model = this.descriptor.model
|
|
470
|
+
? `${this.descriptor.model.provider}/${this.descriptor.model.id}`
|
|
471
|
+
: "";
|
|
472
|
+
this.mdnsBroadcast = await startBroadcast({
|
|
473
|
+
serviceType: this.cfg.discovery.mdns.serviceType,
|
|
474
|
+
name: this.descriptor.agentName,
|
|
475
|
+
port: this.descriptor.port,
|
|
476
|
+
txt: txtRecord({ url: this.descriptor.url, cwd: this.descriptor.cwd, model }),
|
|
477
|
+
});
|
|
478
|
+
this.mdnsDiscovery = await startDiscovery({
|
|
479
|
+
serviceType: this.cfg.discovery.mdns.serviceType,
|
|
480
|
+
onUp: (peer) => {
|
|
481
|
+
// Dedupe by URL (or name:host:port composite); keep the freshest.
|
|
482
|
+
const key = mdnsPeerKey(peer);
|
|
483
|
+
const i = this.mdnsPeers.findIndex((p) => mdnsPeerKey(p) === key);
|
|
484
|
+
if (i >= 0) this.mdnsPeers[i] = peer;
|
|
485
|
+
else this.mdnsPeers.push(peer);
|
|
486
|
+
},
|
|
487
|
+
onDown: (gone) => {
|
|
488
|
+
// Remove the departed peer so the list doesn't grow unbounded.
|
|
489
|
+
this.mdnsPeers = this.mdnsPeers.filter(
|
|
490
|
+
(p) => !(p.name === gone.name && p.host === gone.host && p.port === gone.port),
|
|
491
|
+
);
|
|
492
|
+
},
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** Register this session to the upstream a2a-switchboard gateways (discovery.gateway
|
|
498
|
+
* + discovery.gateways config). One upstream per enabled entry. */
|
|
499
|
+
private async startGatewayUpstream(): Promise<void> {
|
|
500
|
+
const { gatewayEntries } = await import("./config.js");
|
|
501
|
+
const entries = gatewayEntries(this.cfg).filter((e) => e.entry.enabled !== false);
|
|
502
|
+
if (entries.length === 0) return;
|
|
503
|
+
const { GatewayUpstream } = await import("./gateway.js");
|
|
504
|
+
for (const { key, entry } of entries) {
|
|
505
|
+
let gw = entry;
|
|
506
|
+
if (!gw.url || !gw.token) continue;
|
|
507
|
+
// Unique name per session (name-port) unless explicitly pinned — sessions
|
|
508
|
+
// on the same machine share config, and one gateway entry per live session
|
|
509
|
+
// beats last-registration-wins.
|
|
510
|
+
// Same name derivation as the local session (sessionName) — gateway
|
|
511
|
+
// registration should not diverge (pinned wins, else host-port).
|
|
512
|
+
// A per-gateway pinned name (discovery.gateways.<key>.name) still wins.
|
|
513
|
+
const name = gw.name || this.sessionName();
|
|
514
|
+
// Dedicated per-session inbound token: when the entry pins no
|
|
515
|
+
// upstreamToken, mint one per server start and accept it inbound. The
|
|
516
|
+
// switchboard presents it when proxying TO us — the static sharedToken
|
|
517
|
+
// then only serves the local mesh, never leaves this machine.
|
|
518
|
+
// Map key is unique per gateway ENTRY whenever more than one entry
|
|
519
|
+
// mints (pinned or auto names can still collide across gateways):
|
|
520
|
+
// count entries that will mint (no explicit upstreamToken), and suffix
|
|
521
|
+
// -key when >1 — a single minter keeps the stable name identity.
|
|
522
|
+
const minters = entries.filter((e) => !e.entry.upstreamToken);
|
|
523
|
+
const inboundId = minters.length > 1 ? `${name}-${key}` : name;
|
|
524
|
+
if (!gw.upstreamToken) {
|
|
525
|
+
const minted = `agw-${uuid().replace(/-/g, "").slice(0, 24)}`;
|
|
526
|
+
// Server-side map, NOT cfg.server.peerTokens: mutating the config
|
|
527
|
+
// mid-session would flip localhostOnly() (anonymous loopback peers
|
|
528
|
+
// suddenly 401) and publicUrl()'s bind clamp. authenticate() consults
|
|
529
|
+
// this map via extraTokens — lookup only, never for the hasTokens
|
|
530
|
+
// decision.
|
|
531
|
+
this.mintedInboundTokens[inboundId] = minted;
|
|
532
|
+
gw = { ...gw, upstreamToken: minted };
|
|
533
|
+
}
|
|
534
|
+
const upstream = new GatewayUpstream(
|
|
535
|
+
{
|
|
536
|
+
...gw,
|
|
537
|
+
name,
|
|
538
|
+
key,
|
|
539
|
+
// Persists the minted caller_token (<piDir>/a2a_gateways/<key>.json)
|
|
540
|
+
// so restarts heartbeat with PATCH instead of re-minting.
|
|
541
|
+
piDir: this.piDir,
|
|
542
|
+
// The gateway directory copies capabilities/skills from the registered
|
|
543
|
+
// card — send the real Agent Card, not the local-registry descriptor.
|
|
544
|
+
callTimeoutMs: this.cfg.timeouts.send,
|
|
545
|
+
// Exact-match self-filter for the default auto-name — passed even
|
|
546
|
+
// when the user pinned a name, so a stale auto-named entry from a
|
|
547
|
+
// previous run is still filtered.
|
|
548
|
+
autoName: `${this.baseName()}-${this.boundPort}`,
|
|
549
|
+
} as import("./gateway.js").GatewayConfig,
|
|
550
|
+
() => this.buildCard() as unknown as Record<string, unknown>,
|
|
551
|
+
this.onError,
|
|
552
|
+
// Peer-directory overlay: refreshed after each heartbeat, cleared on stop.
|
|
553
|
+
(peers) => updateGatewayPeers(key, peers),
|
|
554
|
+
// Lifecycle status (channel open, …) → host transcript like the
|
|
555
|
+
// registration message, not raw console output.
|
|
556
|
+
(msg) => {
|
|
557
|
+
if (this.onStatus) {
|
|
558
|
+
try {
|
|
559
|
+
this.onStatus(msg);
|
|
560
|
+
} catch {
|
|
561
|
+
console.error(msg);
|
|
562
|
+
}
|
|
563
|
+
} else {
|
|
564
|
+
console.error(msg);
|
|
565
|
+
}
|
|
566
|
+
},
|
|
567
|
+
// Fires on the transition to registered — including a late beat that
|
|
568
|
+
// self-heals after start() returned false (gateway down at session
|
|
569
|
+
// start). Same surface as a successful start(): publish the
|
|
570
|
+
// gateway-issued name (a 409 self-heal rename may have changed it —
|
|
571
|
+
// publishing the pre-rename name would advertise a caller identity
|
|
572
|
+
// the gateway never registered) and emit the registration line.
|
|
573
|
+
(registeredName, state) => {
|
|
574
|
+
setGatewayRegistrationName(registeredName, key);
|
|
575
|
+
const pending = state === "pending";
|
|
576
|
+
let host = gw.url;
|
|
577
|
+
try {
|
|
578
|
+
host = new URL(gw.url).host;
|
|
579
|
+
} catch {
|
|
580
|
+
/* keep raw url */
|
|
581
|
+
}
|
|
582
|
+
const msg =
|
|
583
|
+
`[a2a] registered to a2a-switchboard ${key}@${host} as ${registeredName}` +
|
|
584
|
+
(pending ? " (pending admin acceptance — not yet listed for peers)" : "");
|
|
585
|
+
if (this.onStatus) {
|
|
586
|
+
try {
|
|
587
|
+
this.onStatus(msg);
|
|
588
|
+
return;
|
|
589
|
+
} catch {
|
|
590
|
+
/* fall back to console */
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
console.log(msg);
|
|
594
|
+
},
|
|
595
|
+
);
|
|
596
|
+
this.gatewayUpstreams.set(key, upstream);
|
|
597
|
+
// The onRegistered callback above announces success (immediately, or on
|
|
598
|
+
// a later self-healing beat if the first register failed) — nothing to
|
|
599
|
+
// do with start()'s return value.
|
|
600
|
+
// Fire-and-forget: upstream.start() → connect() → register can wait on
|
|
601
|
+
// a 10s network timeout (and reconnect in a loop) when the switchboard
|
|
602
|
+
// is unreachable. Awaiting it stalls session start (and the first
|
|
603
|
+
// prompt) for that entire window. The 60s heartbeat self-heals
|
|
604
|
+
// registration on its own, and the status callback above announces
|
|
605
|
+
// success/failure — awaiting buys nothing. Rejections are swallowed:
|
|
606
|
+
// start() never rejects (connect catches internally), but keep the
|
|
607
|
+
// handler so a future code change can't turn this into an unhandled
|
|
608
|
+
// rejection.
|
|
609
|
+
void upstream.start(this.publicUrl()).catch(() => { /* heartbeat retries */ });
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
private async stopGatewayUpstream(): Promise<void> {
|
|
614
|
+
if (this.gatewayUpstreams.size === 0) return;
|
|
615
|
+
const upstreams = [...this.gatewayUpstreams.entries()];
|
|
616
|
+
this.gatewayUpstreams.clear();
|
|
617
|
+
// Parallel stop: each upstream's DELETE is bounded (DEREG_TIMEOUT_MS) but
|
|
618
|
+
// sequential stops made /reload and session_shutdown wait N×timeout.
|
|
619
|
+
await Promise.all(upstreams.map(([key, upstream]) =>
|
|
620
|
+
upstream.stop().finally(() => setGatewayRegistrationName(null, key)),
|
|
621
|
+
));
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** Stop local-registry declaration + mDNS. */
|
|
625
|
+
private async stopDiscovery(): Promise<void> {
|
|
626
|
+
if (this.heartbeatTimer) {
|
|
627
|
+
clearInterval(this.heartbeatTimer);
|
|
628
|
+
this.heartbeatTimer = null;
|
|
629
|
+
}
|
|
630
|
+
if (this.cfg.discovery.local.enabled) {
|
|
631
|
+
unregister(this.pid, this.piDir);
|
|
632
|
+
}
|
|
633
|
+
if (this.mdnsBroadcast) {
|
|
634
|
+
await this.mdnsBroadcast.stop();
|
|
635
|
+
this.mdnsBroadcast = null;
|
|
636
|
+
}
|
|
637
|
+
if (this.mdnsDiscovery) {
|
|
638
|
+
await this.mdnsDiscovery.stop();
|
|
639
|
+
this.mdnsDiscovery = null;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
async start(): Promise<{ host: string; port: number; url: string }> {
|
|
644
|
+
if (this.http) {
|
|
645
|
+
return { host: resolveBindHost(this.cfg), port: this.boundPort ?? this.cfg.server.port, url: this.publicUrl() };
|
|
646
|
+
}
|
|
647
|
+
// Retention sweep for child transcripts (fleet task #252): they carry
|
|
648
|
+
// everything a dispatched worker read, so bound their lifetime. Runs
|
|
649
|
+
// unconditionally (also cleans up after transcripts were later disabled)
|
|
650
|
+
// and is best-effort — housekeeping must never block the server.
|
|
651
|
+
try {
|
|
652
|
+
sweepChildTranscripts(childTranscriptDir(this.piDir), this.cfg.server.childTranscriptRetentionDays);
|
|
653
|
+
} catch {
|
|
654
|
+
/* best-effort */
|
|
655
|
+
}
|
|
656
|
+
const host = resolveBindHost(this.cfg);
|
|
657
|
+
this.loopbackBind = LOOPBACK.has(host);
|
|
658
|
+
const configuredPort = this.cfg.server.port;
|
|
659
|
+
const fallback = Math.max(0, this.cfg.server.portFallback);
|
|
660
|
+
|
|
661
|
+
// Try the configured port, then climb (port+1 … port+fallback), then fall
|
|
662
|
+
// back to OS-assigned (0). Mirrors vite/webpack-dev-server "port busy → next".
|
|
663
|
+
const attempts: number[] = [];
|
|
664
|
+
if (configuredPort > 0) {
|
|
665
|
+
for (let i = 0; i <= fallback; i++) attempts.push(configuredPort + i);
|
|
666
|
+
}
|
|
667
|
+
attempts.push(0); // last resort: OS assigns a free port
|
|
668
|
+
|
|
669
|
+
let lastErr: unknown = null;
|
|
670
|
+
for (const port of attempts) {
|
|
671
|
+
const srv = createServer((req, res) => this.handle(req, res));
|
|
672
|
+
try {
|
|
673
|
+
await new Promise<void>((resolve, reject) => {
|
|
674
|
+
srv.once("error", reject);
|
|
675
|
+
srv.listen(port, host, () => {
|
|
676
|
+
srv.removeListener("error", reject);
|
|
677
|
+
resolve();
|
|
678
|
+
});
|
|
679
|
+
});
|
|
680
|
+
this.http = srv;
|
|
681
|
+
this.boundPort = (srv.address() as { port: number })?.port ?? port;
|
|
682
|
+
await this.startDiscovery();
|
|
683
|
+
await this.startGatewayUpstream();
|
|
684
|
+
return { host, port: this.boundPort, url: this.publicUrl() };
|
|
685
|
+
} catch (e: any) {
|
|
686
|
+
lastErr = e;
|
|
687
|
+
// EADDRINUSE → close this half-bound server and try the next port.
|
|
688
|
+
try {
|
|
689
|
+
srv.close();
|
|
690
|
+
} catch {
|
|
691
|
+
/* ignore */
|
|
692
|
+
}
|
|
693
|
+
if (e?.code !== "EADDRINUSE") {
|
|
694
|
+
// Non-port error (permission, bad host, …) — don't keep climbing.
|
|
695
|
+
throw e;
|
|
696
|
+
}
|
|
697
|
+
// Last attempt (port 0) failing with EADDRINUSE is impossible-ish, but
|
|
698
|
+
// if the OS rejected everything, surface the last real error.
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
throw lastErr instanceof Error
|
|
702
|
+
? lastErr
|
|
703
|
+
: new Error("A2A server: no free port available");
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
async stop(): Promise<void> {
|
|
707
|
+
if (!this.http) return;
|
|
708
|
+
// Abort all running tasks so their runners stop promptly.
|
|
709
|
+
for (const st of this.store.list()) {
|
|
710
|
+
const s = this.store.get(st.id);
|
|
711
|
+
if (s?.controller && !s.done) s.controller.abort();
|
|
712
|
+
}
|
|
713
|
+
// Stop accepting + force-close lingering connections (SSE streams, idle
|
|
714
|
+
// keep-alive). closeAllConnections() lands the callback quickly instead of
|
|
715
|
+
// hanging on open connections.
|
|
716
|
+
await new Promise<void>((resolve) => {
|
|
717
|
+
this.http!.close(() => resolve());
|
|
718
|
+
try {
|
|
719
|
+
this.http!.closeAllConnections();
|
|
720
|
+
} catch {
|
|
721
|
+
/* Node < 18.2 fallback — close() will drain normally */
|
|
722
|
+
}
|
|
723
|
+
});
|
|
724
|
+
this.http = null;
|
|
725
|
+
this.boundPort = null;
|
|
726
|
+
await this.stopGatewayUpstream();
|
|
727
|
+
await this.stopDiscovery();
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
get url(): string {
|
|
731
|
+
// When stopped, don't advertise a configured-but-unbound port.
|
|
732
|
+
if (!this.http) return "";
|
|
733
|
+
return this.publicUrl();
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** The ACTUAL port this server bound (differs from cfg.server.port after
|
|
737
|
+
* fallback). null when not started. */
|
|
738
|
+
get port(): number | null {
|
|
739
|
+
return this.boundPort;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/** This session's callable name (pinned agentName or auto `<host>-<port>`). */
|
|
743
|
+
get name(): string {
|
|
744
|
+
return this.sessionName();
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/** For tests: how many tasks are currently running. */
|
|
748
|
+
get runningCount(): number {
|
|
749
|
+
return this.running;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// -------------------------------------------------------------------------
|
|
753
|
+
// HTTP handling
|
|
754
|
+
// -------------------------------------------------------------------------
|
|
755
|
+
|
|
756
|
+
private isLoopbackHost(host: string | undefined): boolean {
|
|
757
|
+
if (!host) return false;
|
|
758
|
+
// Strip port and IPv6 brackets: "127.0.0.1:9910" / "[::1]:9910" / "localhost" / "::1".
|
|
759
|
+
// Bracketed IPv6 must be split on "]" BEFORE any ":" split — "[::1]:9910".split(":")[0]
|
|
760
|
+
// would yield "[".
|
|
761
|
+
let h = host.trim().toLowerCase();
|
|
762
|
+
if (h.startsWith("[")) {
|
|
763
|
+
const end = h.indexOf("]");
|
|
764
|
+
if (end === -1) return false; // malformed bracketed host
|
|
765
|
+
h = h.slice(1, end);
|
|
766
|
+
} else if ((h.match(/:/g) || []).length > 1) {
|
|
767
|
+
// Bare IPv6 (unbracketed, portless) — compare whole host below.
|
|
768
|
+
} else {
|
|
769
|
+
h = h.split(":")[0]!; // host:port
|
|
770
|
+
}
|
|
771
|
+
return LOOPBACK.has(h);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
private isLoopbackOrigin(origin: string | undefined): boolean {
|
|
775
|
+
if (!origin) return true; // no Origin (non-browser client) — fine
|
|
776
|
+
try {
|
|
777
|
+
return this.isLoopbackHost(new URL(origin).hostname);
|
|
778
|
+
} catch {
|
|
779
|
+
return false; // unparsable Origin — reject (defensive)
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
784
|
+
try {
|
|
785
|
+
// DNS-rebinding / CSRF guard (see security review 2026-08-16):
|
|
786
|
+
// - In localhost-only mode the Host header must be loopback, or an
|
|
787
|
+
// attacker domain resolving to 127.0.0.1 still gets rejected.
|
|
788
|
+
// - A non-loopback Origin means a browser page is driving us — reject
|
|
789
|
+
// (browser cross-origin requests can't set custom headers without a
|
|
790
|
+
// preflight, so this blocks the drive-by CSRF path).
|
|
791
|
+
if (localhostOnly(this.cfg) && !this.isLoopbackHost(req.headers.host)) {
|
|
792
|
+
return this.send(res, 403, { error: "forbidden host" });
|
|
793
|
+
}
|
|
794
|
+
if (!this.isLoopbackOrigin(req.headers.origin)) {
|
|
795
|
+
return this.send(res, 403, { error: "forbidden origin" });
|
|
796
|
+
}
|
|
797
|
+
const url = (req.url || "/").split("?")[0]!.replace(/\/+$/, "") || "/";
|
|
798
|
+
if (req.method === "GET") return this.handleGet(url, req, res);
|
|
799
|
+
if (req.method === "POST") {
|
|
800
|
+
// Require a JSON-ish content-type: browser "simple requests" can only
|
|
801
|
+
// send text/plain, form-urlencoded or multipart without preflight —
|
|
802
|
+
// rejecting those closes the CSRF body-injection vector. Missing
|
|
803
|
+
// content-type is tolerated (curl -d without -H sends
|
|
804
|
+
// application/x-www-form-urlencoded, which we DO reject; a truly bare
|
|
805
|
+
// POST is parsed and JSON.parse fails harmlessly).
|
|
806
|
+
const ct = String(req.headers["content-type"] || "").toLowerCase();
|
|
807
|
+
if (ct && !ct.includes("json")) {
|
|
808
|
+
return this.send(res, 415, { error: "content-type must be application/json" });
|
|
809
|
+
}
|
|
810
|
+
return this.handlePost(req, res);
|
|
811
|
+
}
|
|
812
|
+
return this.send(res, 405, { error: "method not allowed" });
|
|
813
|
+
} catch (e: any) {
|
|
814
|
+
return this.send(res, 500, { error: "internal", message: e?.message });
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/** #9: GET endpoints must authenticate — the enriched card leaks pid/cwd/model
|
|
819
|
+
* and /metrics leaks operational data. authenticate() returns null only when
|
|
820
|
+
* a token is REQUIRED and not presented; the plain card still goes out
|
|
821
|
+
* anonymously so discovery keeps working. /metrics requires auth. */
|
|
822
|
+
private getIdentity(req: IncomingMessage): string | null {
|
|
823
|
+
return authenticateInfo({
|
|
824
|
+
authHeader: req.headers["authorization"],
|
|
825
|
+
clientIp: (req.socket.remoteAddress || "").replace(/^::ffff:/, ""),
|
|
826
|
+
peerTokens: this.cfg.server.peerTokens,
|
|
827
|
+
sharedToken: this.cfg.server.sharedToken,
|
|
828
|
+
extraTokens: this.mintedInboundTokens,
|
|
829
|
+
identityHeader: req.headers[IDENTITY_HEADER],
|
|
830
|
+
loopbackBind: this.loopbackBind,
|
|
831
|
+
}).identity;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
private handleGet(url: string, req: IncomingMessage, res: ServerResponse): void {
|
|
835
|
+
if (url === "/.well-known/agent-card.json" || url === "/.well-known/agent.json") {
|
|
836
|
+
const identity = this.getIdentity(req);
|
|
837
|
+
return this.send(res, 200, this.buildCard(identity === null));
|
|
838
|
+
}
|
|
839
|
+
if (url === "/health" || url === "/") {
|
|
840
|
+
return this.send(res, 200, { status: "ok", agent: this.sessionName() });
|
|
841
|
+
}
|
|
842
|
+
if (url === "/metrics") {
|
|
843
|
+
if (this.getIdentity(req) === null) {
|
|
844
|
+
return this.send(res, 401, { error: "unauthorized" });
|
|
845
|
+
}
|
|
846
|
+
return this.send(res, 200, metrics.snapshot());
|
|
847
|
+
}
|
|
848
|
+
return this.send(res, 404, { error: "not found" });
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
private async handlePost(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
852
|
+
const clientIp = (req.socket.remoteAddress || "").replace(/^::ffff:/, "");
|
|
853
|
+
const auth = authenticateInfo({
|
|
854
|
+
authHeader: req.headers["authorization"],
|
|
855
|
+
clientIp,
|
|
856
|
+
peerTokens: this.cfg.server.peerTokens,
|
|
857
|
+
sharedToken: this.cfg.server.sharedToken,
|
|
858
|
+
extraTokens: this.mintedInboundTokens,
|
|
859
|
+
identityHeader: req.headers[IDENTITY_HEADER],
|
|
860
|
+
loopbackBind: this.loopbackBind,
|
|
861
|
+
});
|
|
862
|
+
const identity = auth.identity;
|
|
863
|
+
if (identity === null) {
|
|
864
|
+
return this.send(res, 401, jsonrpcError(null, -32050, "unauthorized"));
|
|
865
|
+
}
|
|
866
|
+
if (!isTrustedPeer(identity, this.cfg)) {
|
|
867
|
+
return this.send(res, 403, jsonrpcError(null, -32052, "untrusted peer"));
|
|
868
|
+
}
|
|
869
|
+
if (!this.limiter.check(identity)) {
|
|
870
|
+
metrics.rateLimited += 1;
|
|
871
|
+
return this.send(res, 429, jsonrpcError(null, -32051, "rate limited"));
|
|
872
|
+
}
|
|
873
|
+
// Framing context for the inbound wrapper (fleet task #322): how the
|
|
874
|
+
// caller connected and how its identity was derived.
|
|
875
|
+
const framing: InboundFraming = {
|
|
876
|
+
transport: transportName(clientIp),
|
|
877
|
+
provenance: auth.provenance ?? "address",
|
|
878
|
+
};
|
|
879
|
+
|
|
880
|
+
const body = await this.readBody(req);
|
|
881
|
+
let rpc: any;
|
|
882
|
+
try {
|
|
883
|
+
rpc = JSON.parse(body);
|
|
884
|
+
} catch {
|
|
885
|
+
return this.send(res, 200, jsonrpcError(null, -32700, "parse error"));
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
const method = String(rpc.method || "");
|
|
889
|
+
const params = rpc.params || {};
|
|
890
|
+
const id = rpc.id ?? null;
|
|
891
|
+
|
|
892
|
+
// Normalize method aliases (v1.0 PascalCase ↔ pre-1.0 path).
|
|
893
|
+
const norm = method.toLowerCase().replace(/[/_.-]/g, "");
|
|
894
|
+
// v1.0 methods ("SendMessage", "ListTasks", …) speak the v1.0 wire shapes;
|
|
895
|
+
// the pre-1.0 aliases ("message/send", "tasks/list", …) keep the legacy
|
|
896
|
+
// shapes old peers were built against.
|
|
897
|
+
const isV1 = (v1Norm: string): boolean => norm === v1Norm;
|
|
898
|
+
|
|
899
|
+
if (norm === "messagesend" || norm === "sendmessage") {
|
|
900
|
+
// Concurrency cap (blocking pool): reject when too many blocking tasks
|
|
901
|
+
// are already running. Detached tasks do not compete for this pool.
|
|
902
|
+
if (this.running >= this.cfg.server.maxConcurrent) {
|
|
903
|
+
return this.send(
|
|
904
|
+
res,
|
|
905
|
+
503,
|
|
906
|
+
jsonrpcError(id, -32053, `server busy: max ${this.cfg.server.maxConcurrent} concurrent tasks`),
|
|
907
|
+
);
|
|
908
|
+
}
|
|
909
|
+
const r = await this.messageSend(params, identity, undefined, framing);
|
|
910
|
+
// A2A v1.0: the SendMessage result is the oneof {"task": …} | {"message": …},
|
|
911
|
+
// never a bare Task; the pre-1.0 alias keeps returning the bare Task.
|
|
912
|
+
return this.send(res, 200, jsonrpcResult(id, isV1("sendmessage") ? sendTaskResponse(r) : r));
|
|
913
|
+
}
|
|
914
|
+
if (norm === "messagestream" || norm === "sendstreamingmessage") {
|
|
915
|
+
return this.messageStream(params, identity, res, id, isV1("sendstreamingmessage"), framing);
|
|
916
|
+
}
|
|
917
|
+
if (norm === "tasksget" || norm === "gettask") {
|
|
918
|
+
const st = this.store.get(String(params.id ?? ""));
|
|
919
|
+
if (!st) return this.send(res, 200, jsonrpcError(id, -32001, "task not found"));
|
|
920
|
+
// Per-identity ownership (#10): a peer may only fetch its own tasks.
|
|
921
|
+
if (st.identity !== identity) return this.send(res, 200, jsonrpcError(id, -32001, "task not found"));
|
|
922
|
+
return this.send(res, 200, jsonrpcResult(id, st.task));
|
|
923
|
+
}
|
|
924
|
+
if (norm === "taskslist" || norm === "listtasks") {
|
|
925
|
+
// Per-identity ownership (#10): only the caller's own tasks are listed.
|
|
926
|
+
const mine = this.store.list().filter((t) => this.store.get(t.id)?.identity === identity);
|
|
927
|
+
// A2A v1.0: ListTasksResponse carries full Task objects; the pre-1.0
|
|
928
|
+
// alias keeps the {id, state} stubs it always returned.
|
|
929
|
+
const tasks = isV1("listtasks") ? mine : mine.map((t) => ({ id: t.id, state: t.status.state }));
|
|
930
|
+
return this.send(res, 200, jsonrpcResult(id, { tasks }));
|
|
931
|
+
}
|
|
932
|
+
if (norm === "taskscancel" || norm === "canceltask") {
|
|
933
|
+
const st = this.store.get(String(params.id ?? ""));
|
|
934
|
+
if (!st) return this.send(res, 200, jsonrpcError(id, -32001, "task not found"));
|
|
935
|
+
// Per-identity ownership (#10): a peer may only cancel its own tasks.
|
|
936
|
+
if (st.identity !== identity) return this.send(res, 200, jsonrpcError(id, -32001, "task not found"));
|
|
937
|
+
if (st.done) return this.send(res, 200, jsonrpcError(id, -32002, "task not cancelable"));
|
|
938
|
+
st.userCanceled = true; // so messageSend's catch classifies as CANCELED, not timeout-FAILED
|
|
939
|
+
st.controller?.abort();
|
|
940
|
+
// Set the state ourselves — the catch in messageSend will run async and
|
|
941
|
+
// we must return CANCELED in THIS response, not the pre-abort WORKING.
|
|
942
|
+
this.store.update(st.task.id, (t) => {
|
|
943
|
+
t.status.state = STATE_CANCELED;
|
|
944
|
+
});
|
|
945
|
+
// NOTE: do NOT bump metrics here — messageSend's catch handles it once.
|
|
946
|
+
return this.send(res, 200, jsonrpcResult(id, st.task));
|
|
947
|
+
}
|
|
948
|
+
if (norm === "taskssubscribe" || norm === "subscribetotask") {
|
|
949
|
+
// Resubscribe via SSE — same shape as message/stream.
|
|
950
|
+
return this.taskSubscribe(params, identity, res, id, isV1("subscribetotask"));
|
|
951
|
+
}
|
|
952
|
+
return this.send(res, 200, jsonrpcError(id, -32601, `method not found: ${method}`));
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
private async messageSend(
|
|
956
|
+
params: any,
|
|
957
|
+
identity: string,
|
|
958
|
+
externalSignal?: AbortSignal,
|
|
959
|
+
framing?: InboundFraming,
|
|
960
|
+
): Promise<any> {
|
|
961
|
+
const msg: Message = params.message ?? params;
|
|
962
|
+
const inboundText = extractText(params);
|
|
963
|
+
const contextId = String(params.contextId || msg.contextId || newContextId());
|
|
964
|
+
const taskId = newTaskId();
|
|
965
|
+
// A2A v1.0 §3.2.2 SendMessageConfiguration.returnImmediately — the caller
|
|
966
|
+
// asks for an immediate in-progress Task instead of waiting for the
|
|
967
|
+
// terminal state (submit-and-poll).
|
|
968
|
+
const returnImmediately = wantsImmediateReturn(params);
|
|
969
|
+
|
|
970
|
+
// Anti-loop: cap per-context turns.
|
|
971
|
+
if (!this.antiLoop.record(contextId)) {
|
|
972
|
+
metrics.antiLoopTriggers += 1;
|
|
973
|
+
const t = buildTask({ id: taskId, contextId, state: STATE_REJECTED });
|
|
974
|
+
this.store.add(taskId, { task: t, done: true, identity, subscribeWatchers: [] });
|
|
975
|
+
audit({ piDir: this.piDir, direction: "inbound", identity, taskId, text: "[anti-loop rejected]" });
|
|
976
|
+
return t;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
// Create the task (SUBMITTED → WORKING).
|
|
980
|
+
const task = buildTask({ id: taskId, contextId, state: STATE_WORKING });
|
|
981
|
+
const controller = new AbortController();
|
|
982
|
+
const st: StoredTask = { task, controller, done: false, identity, subscribeWatchers: [] };
|
|
983
|
+
this.store.add(taskId, st);
|
|
984
|
+
audit({ piDir: this.piDir, direction: "inbound", identity, taskId, text: inboundText });
|
|
985
|
+
this.onActivity?.({ type: "arrived", taskId, identity, text: inboundText, contextId });
|
|
986
|
+
|
|
987
|
+
// If an external abort fires (client disconnect on streams, or tasks/cancel
|
|
988
|
+
// on a streaming task), propagate it to the runner's controller.
|
|
989
|
+
if (externalSignal) {
|
|
990
|
+
const onExternal = () => controller.abort();
|
|
991
|
+
externalSignal.addEventListener("abort", onExternal, { once: true });
|
|
992
|
+
controller.signal.addEventListener("abort", () => externalSignal.removeEventListener("abort", onExternal), { once: true });
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
// Admission: promote to the detached pool only while it has capacity.
|
|
996
|
+
// A full detached pool means the returnImmediately hint is ignored and
|
|
997
|
+
// the caller waits for the terminal state (A2A v1.0 §3.2.2 lets the
|
|
998
|
+
// server treat the hint as advisory) — never a 503 while blocking slots
|
|
999
|
+
// remain, which is what re-checking a SHARED gate here would produce.
|
|
1000
|
+
const detached = returnImmediately && this.detachedRunning < this.cfg.server.maxConcurrent;
|
|
1001
|
+
if (detached) this.detachedRunning += 1;
|
|
1002
|
+
else this.running += 1;
|
|
1003
|
+
|
|
1004
|
+
// Blocking (default): await the run and return the terminal Task.
|
|
1005
|
+
// Non-blocking (returnImmediately): return the in-progress Task as an
|
|
1006
|
+
// ACK right away and let the run continue detached from the HTTP request
|
|
1007
|
+
// — the caller polls GetTask / subscribes / cancels by task id, and the
|
|
1008
|
+
// session is no longer bounded by the caller's reply window (detached
|
|
1009
|
+
// runs are supervised by server.asyncTimeoutSec instead).
|
|
1010
|
+
const execution = this.executeTask(st, identity, inboundText, detached, framing);
|
|
1011
|
+
if (detached) {
|
|
1012
|
+
// The detached run continues after this reply returns; nothing else
|
|
1013
|
+
// will ever await `execution`. executeTask never rejects by contract
|
|
1014
|
+
// (every failure is classified into the task state), but that is
|
|
1015
|
+
// discipline, not a type guarantee — a throw on a path outside its
|
|
1016
|
+
// try/catch (a store update, an activity callback, an OOM) would be an
|
|
1017
|
+
// UNOBSERVED rejection that takes the process down (Node's default).
|
|
1018
|
+
// Observe the promise and contain an unexpected throw: best-effort
|
|
1019
|
+
// mark the task FAILED (redacted) so a poller sees the truth instead
|
|
1020
|
+
// of WORKING forever, and never rethrow — this catch is the last
|
|
1021
|
+
// observer of the promise.
|
|
1022
|
+
execution.catch((e) => {
|
|
1023
|
+
try {
|
|
1024
|
+
if (!st.done) {
|
|
1025
|
+
this.store.update(taskId, (t) => {
|
|
1026
|
+
t.status.state = STATE_FAILED;
|
|
1027
|
+
t.status.message = {
|
|
1028
|
+
role: "ROLE_AGENT",
|
|
1029
|
+
parts: [{ text: redactOutbound(`internal error: ${e?.message ?? String(e)}`), mediaType: "text/plain" }],
|
|
1030
|
+
messageId: newContextId(),
|
|
1031
|
+
};
|
|
1032
|
+
});
|
|
1033
|
+
st.done = true;
|
|
1034
|
+
}
|
|
1035
|
+
} catch {
|
|
1036
|
+
/* containment is best-effort */
|
|
1037
|
+
}
|
|
1038
|
+
});
|
|
1039
|
+
return st.task;
|
|
1040
|
+
}
|
|
1041
|
+
return execution;
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
/**
|
|
1045
|
+
* Run one stored task to completion and update the store. Never rejects —
|
|
1046
|
+
* failures are classified into the task state (FAILED/CANCELED) exactly as
|
|
1047
|
+
* the blocking path has always done. The matching admission-pool counter
|
|
1048
|
+
* (`running` for blocking, `detachedRunning` for detached) is held for the
|
|
1049
|
+
* whole execution.
|
|
1050
|
+
*/
|
|
1051
|
+
private async executeTask(
|
|
1052
|
+
st: StoredTask,
|
|
1053
|
+
identity: string,
|
|
1054
|
+
inboundText: string,
|
|
1055
|
+
detached: boolean,
|
|
1056
|
+
framing?: InboundFraming,
|
|
1057
|
+
): Promise<any> {
|
|
1058
|
+
const taskId = st.task.id;
|
|
1059
|
+
const controller = st.controller!;
|
|
1060
|
+
const startedAt = Date.now();
|
|
1061
|
+
// Supervision timer for this run: reply window (blocking) or async window
|
|
1062
|
+
// (detached). Hoisted so the finally can clear it on EVERY settle path —
|
|
1063
|
+
// a timer left armed after a failed run keeps the process alive long
|
|
1064
|
+
// after the suite/server is done (the runner rejects, no abort fires,
|
|
1065
|
+
// nothing clears it: with the 86400s async default that is a full day).
|
|
1066
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
1067
|
+
// Local ground truth for "this run was killed by OUR supervision timer",
|
|
1068
|
+
// set in the timer callback BEFORE the abort so it can never disagree
|
|
1069
|
+
// with the timer. The catch path keys the supervision classification on
|
|
1070
|
+
// this flag, never on the abort reason's TEXT — prefix-matching
|
|
1071
|
+
// "reply timeout" would let any future abort site (or runner error) with
|
|
1072
|
+
// that wording masquerade as a supervision kill.
|
|
1073
|
+
let timedOut = false;
|
|
1074
|
+
try {
|
|
1075
|
+
// Blocking runs are bounded by the reply window (the HTTP request is
|
|
1076
|
+
// holding the caller hostage). Detached runs are bounded by the async
|
|
1077
|
+
// window instead. 0 disables the timer for BOTH windows, documented as
|
|
1078
|
+
// "unbounded / caller-supervised": for the async window that is the
|
|
1079
|
+
// deliberate submit-and-poll contract, and for the reply window it
|
|
1080
|
+
// replaces the pre-async-dispatch degenerate reading of
|
|
1081
|
+
// setTimeout(…, 0) — "instant timeout on every task" — which no
|
|
1082
|
+
// working configuration can have depended on.
|
|
1083
|
+
const timeoutSec = detached ? this.cfg.server.asyncTimeoutSec : this.cfg.server.replyTimeoutSec;
|
|
1084
|
+
if (timeoutSec > 0) {
|
|
1085
|
+
timer = setTimeout(() => {
|
|
1086
|
+
timedOut = true;
|
|
1087
|
+
controller.abort(
|
|
1088
|
+
new Error(
|
|
1089
|
+
detached
|
|
1090
|
+
? `async timeout: exceeded the ${timeoutSec}s detached-task window — session aborted mid-run, result is truncated`
|
|
1091
|
+
: "reply timeout",
|
|
1092
|
+
),
|
|
1093
|
+
);
|
|
1094
|
+
}, timeoutSec * 1000);
|
|
1095
|
+
// Clear on abort too: a runner that ignores its signal and never
|
|
1096
|
+
// settles must not hold the process alive until the timer fires.
|
|
1097
|
+
controller.signal.addEventListener("abort", () => clearTimeout(timer), { once: true });
|
|
1098
|
+
}
|
|
1099
|
+
const wrapped = wrapInbound(identity, inboundText, framing);
|
|
1100
|
+
const runner = this.requireRunner();
|
|
1101
|
+
const out = await runner({
|
|
1102
|
+
message: wrapped,
|
|
1103
|
+
taskId,
|
|
1104
|
+
signal: controller.signal,
|
|
1105
|
+
onProgress: (line) => this.onActivity?.({ type: "progress", taskId, line }),
|
|
1106
|
+
});
|
|
1107
|
+
if (controller.signal.aborted) {
|
|
1108
|
+
// Defense in depth (#247): a runner may return normally even though
|
|
1109
|
+
// its abort signal fired — the stock runner's prompt promise resolves
|
|
1110
|
+
// on session.abort() rather than rejecting, so without this check a
|
|
1111
|
+
// killed worker came back TASK_STATE_COMPLETED with a truncated reply
|
|
1112
|
+
// artifact. COMPLETED must mean the turn actually finished: route any
|
|
1113
|
+
// post-abort return through the failure classification below
|
|
1114
|
+
// (CANCELED for user cancel, FAILED otherwise).
|
|
1115
|
+
const err =
|
|
1116
|
+
controller.signal.reason instanceof Error
|
|
1117
|
+
? controller.signal.reason
|
|
1118
|
+
: new Error("task aborted before completion");
|
|
1119
|
+
this.attachTranscript(err, out);
|
|
1120
|
+
throw err;
|
|
1121
|
+
}
|
|
1122
|
+
const finalState = out.inputRequired ? STATE_INPUT_REQUIRED : STATE_COMPLETED;
|
|
1123
|
+
// Outbound redaction: replies cross the trust boundary back to a peer,
|
|
1124
|
+
// so scrub credential-shaped substrings (sk-*, ghp_*, bearer …, emails,
|
|
1125
|
+
// JWTs) before they are stored as artifacts or returned to the caller.
|
|
1126
|
+
const reply = redactOutbound(out.reply ?? "");
|
|
1127
|
+
this.store.update(taskId, (t) => {
|
|
1128
|
+
t.status.state = finalState;
|
|
1129
|
+
t.artifacts = [
|
|
1130
|
+
{
|
|
1131
|
+
artifactId: "reply",
|
|
1132
|
+
name: "reply",
|
|
1133
|
+
parts: [{ text: reply, mediaType: "text/plain" }],
|
|
1134
|
+
},
|
|
1135
|
+
];
|
|
1136
|
+
});
|
|
1137
|
+
st.done = true;
|
|
1138
|
+
metrics.tasksCompleted += 1;
|
|
1139
|
+
this.auditTranscript(taskId, identity, out.transcriptPath, out.stepCount);
|
|
1140
|
+
this.onActivity?.({
|
|
1141
|
+
type: "completed",
|
|
1142
|
+
taskId,
|
|
1143
|
+
state: finalState,
|
|
1144
|
+
replyPreview: preview(reply),
|
|
1145
|
+
elapsedMs: Date.now() - startedAt,
|
|
1146
|
+
});
|
|
1147
|
+
return st.task; // bare Task as the JSON-RPC result (legacy-compatible)
|
|
1148
|
+
} catch (e: any) {
|
|
1149
|
+
const aborted = controller.signal.aborted;
|
|
1150
|
+
// Distinguish user-initiated cancel (CANCELED) from system timeout/failure (FAILED).
|
|
1151
|
+
const state = aborted && st.userCanceled ? STATE_CANCELED : STATE_FAILED;
|
|
1152
|
+
this.auditTranscript(taskId, identity, (e as any)?.transcriptPath, (e as any)?.stepCount);
|
|
1153
|
+
// A supervision timeout's ground truth is the local `timedOut` flag
|
|
1154
|
+
// (set by OUR timer callback), never the abort reason's TEXT — the
|
|
1155
|
+
// reason carries the descriptive "reply/async timeout: … the Ns window"
|
|
1156
|
+
// message we abort with, and a runner rejecting with its own error
|
|
1157
|
+
// must not be able to spoof that wording into a supervision
|
|
1158
|
+
// classification. Client-disconnect aborts carry a generic AbortError,
|
|
1159
|
+
// and cancels are classified above (userCanceled). timedOut implies
|
|
1160
|
+
// aborted — the flag is set only in the callback that aborts.
|
|
1161
|
+
const reason = controller.signal.reason;
|
|
1162
|
+
const reasonMsg = timedOut && !st.userCanceled && reason instanceof Error ? reason.message : undefined;
|
|
1163
|
+
this.store.update(taskId, (t) => {
|
|
1164
|
+
// Don't clobber a cancel-handler-set CANCELED state with an error message.
|
|
1165
|
+
t.status.state = state;
|
|
1166
|
+
if (state !== STATE_CANCELED) {
|
|
1167
|
+
t.status.message = {
|
|
1168
|
+
role: "ROLE_AGENT",
|
|
1169
|
+
// Redacted: error messages can embed reply text (parse failures,
|
|
1170
|
+
// tool errors quoting the payload) — same outbound trust boundary
|
|
1171
|
+
// as the reply artifact.
|
|
1172
|
+
parts: [{ text: redactOutbound(reasonMsg ?? e?.message ?? String(e)), mediaType: "text/plain" }],
|
|
1173
|
+
messageId: newContextId(),
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
});
|
|
1177
|
+
st.done = true;
|
|
1178
|
+
if (state === STATE_CANCELED) {
|
|
1179
|
+
// cancel doesn't count as a failure in completion metrics
|
|
1180
|
+
this.onActivity?.({
|
|
1181
|
+
type: "completed",
|
|
1182
|
+
taskId,
|
|
1183
|
+
state,
|
|
1184
|
+
replyPreview: "(canceled)",
|
|
1185
|
+
elapsedMs: Date.now() - startedAt,
|
|
1186
|
+
});
|
|
1187
|
+
} else {
|
|
1188
|
+
metrics.tasksFailed += 1;
|
|
1189
|
+
this.onActivity?.({
|
|
1190
|
+
type: "failed",
|
|
1191
|
+
taskId,
|
|
1192
|
+
error: e?.message || String(e),
|
|
1193
|
+
elapsedMs: Date.now() - startedAt,
|
|
1194
|
+
});
|
|
1195
|
+
}
|
|
1196
|
+
return st.task;
|
|
1197
|
+
} finally {
|
|
1198
|
+
if (detached) this.detachedRunning -= 1;
|
|
1199
|
+
else this.running -= 1;
|
|
1200
|
+
// The run settled (completed or classified) — the supervision timer's
|
|
1201
|
+
// job is done. Without this, a FAILED run whose runner threw its own
|
|
1202
|
+
// error (no abort → no listener fire) leaked an armed timer that kept
|
|
1203
|
+
// the process alive after the suite finished.
|
|
1204
|
+
clearTimeout(timer);
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
private messageStream(
|
|
1209
|
+
params: any,
|
|
1210
|
+
identity: string,
|
|
1211
|
+
res: ServerResponse,
|
|
1212
|
+
id: any,
|
|
1213
|
+
v1 = false,
|
|
1214
|
+
framing?: InboundFraming,
|
|
1215
|
+
): void {
|
|
1216
|
+
// Concurrency cap: same gate as message/send. Streaming has already sent
|
|
1217
|
+
// 200 + headers, so we emit a JSON-RPC error frame and close the stream.
|
|
1218
|
+
if (this.running >= this.cfg.server.maxConcurrent) {
|
|
1219
|
+
res.writeHead(200, {
|
|
1220
|
+
"Content-Type": "text/event-stream",
|
|
1221
|
+
"Cache-Control": "no-cache",
|
|
1222
|
+
Connection: "keep-alive",
|
|
1223
|
+
"A2A-Version": PROTOCOL_VERSION,
|
|
1224
|
+
});
|
|
1225
|
+
res.write(`data: ${JSON.stringify(jsonrpcError(id, -32053, `server busy: max ${this.cfg.server.maxConcurrent} concurrent tasks`))}\n\n`);
|
|
1226
|
+
try {
|
|
1227
|
+
res.end();
|
|
1228
|
+
} catch {
|
|
1229
|
+
/* ignore */
|
|
1230
|
+
}
|
|
1231
|
+
return;
|
|
1232
|
+
}
|
|
1233
|
+
res.writeHead(200, {
|
|
1234
|
+
"Content-Type": "text/event-stream",
|
|
1235
|
+
"Cache-Control": "no-cache",
|
|
1236
|
+
Connection: "keep-alive",
|
|
1237
|
+
"A2A-Version": PROTOCOL_VERSION,
|
|
1238
|
+
});
|
|
1239
|
+
// Each SSE data line is a JSON-RPC 2.0 response echoing the request id
|
|
1240
|
+
// (A2A v1.0 spec compliance — clients correlate streams by id).
|
|
1241
|
+
const writeSse = (result: any): void => {
|
|
1242
|
+
if (res.destroyed || res.writableEnded) return;
|
|
1243
|
+
try {
|
|
1244
|
+
res.write(`data: ${JSON.stringify(jsonrpcResult(id, result))}\n\n`);
|
|
1245
|
+
} catch {
|
|
1246
|
+
/* res may be destroyed during shutdown */
|
|
1247
|
+
}
|
|
1248
|
+
};
|
|
1249
|
+
const writeErr = (code: number, message: string): void => {
|
|
1250
|
+
if (res.destroyed || res.writableEnded) return;
|
|
1251
|
+
try {
|
|
1252
|
+
res.write(`data: ${JSON.stringify(jsonrpcError(id, code, message))}\n\n`);
|
|
1253
|
+
} catch {
|
|
1254
|
+
/* res may be destroyed during shutdown */
|
|
1255
|
+
}
|
|
1256
|
+
};
|
|
1257
|
+
|
|
1258
|
+
// Abort the underlying task if the client disconnects mid-stream, so the
|
|
1259
|
+
// runner's session stops instead of burning tokens nobody will read.
|
|
1260
|
+
const disconnect = new AbortController();
|
|
1261
|
+
res.on("close", () => disconnect.abort());
|
|
1262
|
+
|
|
1263
|
+
// return_immediately has no effect on streaming operations (A2A v1.0
|
|
1264
|
+
// §3.2.2) — strip it so the stream path keeps its blocking semantics.
|
|
1265
|
+
if (wantsImmediateReturn(params)) {
|
|
1266
|
+
params = {
|
|
1267
|
+
...params,
|
|
1268
|
+
configuration: { ...(params.configuration ?? {}), returnImmediately: false, return_immediately: false },
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
this.messageSend(params, identity, disconnect.signal, framing)
|
|
1273
|
+
.then((task) => {
|
|
1274
|
+
if (v1) {
|
|
1275
|
+
// A2A v1.0: TaskArtifactUpdateEvents deliver the content, then the
|
|
1276
|
+
// terminal TaskStatusUpdateEvent closes the interaction — the last
|
|
1277
|
+
// frame carries taskId/contextId/state, so a client reading only the
|
|
1278
|
+
// final event still learns the identifiers.
|
|
1279
|
+
for (const a of task.artifacts ?? []) writeSse(artifactUpdateEvent(task, a));
|
|
1280
|
+
writeSse(statusUpdateEvent(task, true));
|
|
1281
|
+
} else {
|
|
1282
|
+
// Pre-1.0 alias keeps the legacy shapes (whole Task as statusUpdate,
|
|
1283
|
+
// bare artifact as artifactUpdate).
|
|
1284
|
+
writeSse({ statusUpdate: task });
|
|
1285
|
+
if (task.artifacts) {
|
|
1286
|
+
for (const a of task.artifacts) writeSse({ artifactUpdate: a });
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
})
|
|
1290
|
+
.catch((e: any) => writeErr(-32603, e?.message || String(e)))
|
|
1291
|
+
.finally(() => {
|
|
1292
|
+
metrics.streamsStarted += 1;
|
|
1293
|
+
try {
|
|
1294
|
+
res.end();
|
|
1295
|
+
} catch {
|
|
1296
|
+
/* ignore */
|
|
1297
|
+
}
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
private taskSubscribe(params: any, identity: string, res: ServerResponse, id: any, v1 = false): void {
|
|
1302
|
+
const taskId = String(params.id ?? "");
|
|
1303
|
+
const st = this.store.get(taskId);
|
|
1304
|
+
// Ownership check (#10) BEFORE writing the SSE head, so a foreign peer gets
|
|
1305
|
+
// a proper JSON-RPC error instead of a 200 event-stream that hangs.
|
|
1306
|
+
if (!st || st.identity !== identity) {
|
|
1307
|
+
this.send(res, 200, jsonrpcError(id, -32001, "task not found"));
|
|
1308
|
+
res.end();
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
res.writeHead(200, {
|
|
1312
|
+
"Content-Type": "text/event-stream",
|
|
1313
|
+
"Cache-Control": "no-cache",
|
|
1314
|
+
Connection: "keep-alive",
|
|
1315
|
+
"A2A-Version": PROTOCOL_VERSION,
|
|
1316
|
+
});
|
|
1317
|
+
const writeSse = (result: any): void => {
|
|
1318
|
+
if (res.destroyed || res.writableEnded) return;
|
|
1319
|
+
try {
|
|
1320
|
+
res.write(`data: ${JSON.stringify(jsonrpcResult(id, result))}\n\n`);
|
|
1321
|
+
} catch {
|
|
1322
|
+
/* res may be destroyed during shutdown */
|
|
1323
|
+
}
|
|
1324
|
+
};
|
|
1325
|
+
const writeErr = (code: number, message: string): void => {
|
|
1326
|
+
if (res.destroyed || res.writableEnded) return;
|
|
1327
|
+
try {
|
|
1328
|
+
res.write(`data: ${JSON.stringify(jsonrpcError(id, code, message))}\n\n`);
|
|
1329
|
+
} catch {
|
|
1330
|
+
/* res may be destroyed during shutdown */
|
|
1331
|
+
}
|
|
1332
|
+
};
|
|
1333
|
+
if (!st) {
|
|
1334
|
+
writeErr(-32001, "task not found");
|
|
1335
|
+
res.end();
|
|
1336
|
+
return;
|
|
1337
|
+
}
|
|
1338
|
+
// v1.0: a TaskStatusUpdateEvent {taskId, contextId, status, final}; the
|
|
1339
|
+
// pre-1.0 alias keeps the legacy whole-Task shape. A snapshot of an
|
|
1340
|
+
// already-finished task is the final event of this stream.
|
|
1341
|
+
writeSse(v1 ? statusUpdateEvent(st.task, st.done) : { statusUpdate: st.task });
|
|
1342
|
+
if (st.done) {
|
|
1343
|
+
res.end();
|
|
1344
|
+
return;
|
|
1345
|
+
}
|
|
1346
|
+
const watcher = (t: Task): void =>
|
|
1347
|
+
writeSse(v1 ? statusUpdateEvent(t, TERMINAL_STATES.has(t.status.state)) : { statusUpdate: t });
|
|
1348
|
+
st.subscribeWatchers.push(watcher);
|
|
1349
|
+
const interval = setInterval(() => {
|
|
1350
|
+
if (st.done) {
|
|
1351
|
+
clearInterval(interval);
|
|
1352
|
+
try {
|
|
1353
|
+
res.end();
|
|
1354
|
+
} catch {
|
|
1355
|
+
/* ignore */
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
}, 500);
|
|
1359
|
+
res.on("close", () => {
|
|
1360
|
+
clearInterval(interval);
|
|
1361
|
+
st.subscribeWatchers = st.subscribeWatchers.filter((w) => w !== watcher);
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
/** Stamp transcript forensics (path + step count) onto an error so the
|
|
1366
|
+
* catch path can audit them — the runner attaches the same fields to the
|
|
1367
|
+
* errors it throws itself (fleet task #252). */
|
|
1368
|
+
private attachTranscript(err: unknown, out: { transcriptPath?: string; stepCount?: number }): void {
|
|
1369
|
+
if (!out.transcriptPath) return;
|
|
1370
|
+
try {
|
|
1371
|
+
(err as any).transcriptPath = out.transcriptPath;
|
|
1372
|
+
if (out.stepCount !== undefined) (err as any).stepCount = out.stepCount;
|
|
1373
|
+
} catch {
|
|
1374
|
+
/* best-effort */
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
/** Audit the child transcript's existence at completion/failure so a
|
|
1379
|
+
* post-mortem can go from audit log (or task id) straight to the step
|
|
1380
|
+
* history — no guessing where the transcript lives (fleet task #252). */
|
|
1381
|
+
private auditTranscript(
|
|
1382
|
+
taskId: string,
|
|
1383
|
+
identity: string,
|
|
1384
|
+
transcriptPath: string | undefined,
|
|
1385
|
+
stepCount: number | undefined,
|
|
1386
|
+
): void {
|
|
1387
|
+
if (!transcriptPath) return;
|
|
1388
|
+
audit({
|
|
1389
|
+
piDir: this.piDir,
|
|
1390
|
+
direction: "inbound",
|
|
1391
|
+
identity,
|
|
1392
|
+
taskId,
|
|
1393
|
+
text: `[transcript] ${transcriptPath}${stepCount !== undefined ? ` (${stepCount} steps)` : ""}`,
|
|
1394
|
+
transcriptPath,
|
|
1395
|
+
});
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
private requireRunner(): SessionRunner {
|
|
1399
|
+
if (!this.runner) {
|
|
1400
|
+
throw new Error(
|
|
1401
|
+
"no session runner configured — the inbound server needs a model/registry " +
|
|
1402
|
+
"from the host session to spawn agent sessions. Set a2a.server.enabled after " +
|
|
1403
|
+
"the session is ready, or configure a model.",
|
|
1404
|
+
);
|
|
1405
|
+
}
|
|
1406
|
+
return this.runner;
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
private readBody(req: IncomingMessage): Promise<string> {
|
|
1410
|
+
return new Promise((resolve, reject) => {
|
|
1411
|
+
const chunks: Buffer[] = [];
|
|
1412
|
+
let size = 0;
|
|
1413
|
+
const MAX = 5 * 1024 * 1024; // 5MB cap
|
|
1414
|
+
req.on("data", (c: Buffer) => {
|
|
1415
|
+
size += c.length;
|
|
1416
|
+
if (size > MAX) {
|
|
1417
|
+
req.destroy();
|
|
1418
|
+
reject(new Error("payload too large"));
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
chunks.push(c);
|
|
1422
|
+
});
|
|
1423
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
|
|
1424
|
+
req.on("error", reject);
|
|
1425
|
+
});
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
private send(res: ServerResponse, status: number, body: any): void {
|
|
1429
|
+
const json = JSON.stringify(body);
|
|
1430
|
+
res.writeHead(status, {
|
|
1431
|
+
"Content-Type": "application/json",
|
|
1432
|
+
"A2A-Version": PROTOCOL_VERSION,
|
|
1433
|
+
});
|
|
1434
|
+
res.end(json);
|
|
1435
|
+
}
|
|
1436
|
+
}
|