ceulen 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/extensions/lib/registry.ts +16 -3
  3. package/extensions/modules/a2a/configPanel.ts +435 -0
  4. package/extensions/modules/a2a/index.ts +1117 -0
  5. package/extensions/modules/a2a/lib/activity.ts +173 -0
  6. package/extensions/modules/a2a/lib/client.ts +1061 -0
  7. package/extensions/modules/a2a/lib/config.ts +920 -0
  8. package/extensions/modules/a2a/lib/discovery.ts +158 -0
  9. package/extensions/modules/a2a/lib/gateway.ts +889 -0
  10. package/extensions/modules/a2a/lib/mdns.ts +233 -0
  11. package/extensions/modules/a2a/lib/outcome.ts +48 -0
  12. package/extensions/modules/a2a/lib/persistence.ts +123 -0
  13. package/extensions/modules/a2a/lib/protocol.ts +506 -0
  14. package/extensions/modules/a2a/lib/registry.ts +146 -0
  15. package/extensions/modules/a2a/lib/retry.ts +86 -0
  16. package/extensions/modules/a2a/lib/security.ts +394 -0
  17. package/extensions/modules/a2a/lib/server.ts +1436 -0
  18. package/extensions/modules/a2a/test/activity.test.ts +138 -0
  19. package/extensions/modules/a2a/test/bridge.test.ts +101 -0
  20. package/extensions/modules/a2a/test/broadcast-parse.test.ts +31 -0
  21. package/extensions/modules/a2a/test/chai.ts +101 -0
  22. package/extensions/modules/a2a/test/client.test.ts +856 -0
  23. package/extensions/modules/a2a/test/completion-guard.test.ts +73 -0
  24. package/extensions/modules/a2a/test/config.test.ts +1396 -0
  25. package/extensions/modules/a2a/test/configPanel.test.ts +393 -0
  26. package/extensions/modules/a2a/test/discovery.test.ts +144 -0
  27. package/extensions/modules/a2a/test/extension.test.ts +135 -0
  28. package/extensions/modules/a2a/test/gateway.test.ts +1449 -0
  29. package/extensions/modules/a2a/test/helpers.ts +39 -0
  30. package/extensions/modules/a2a/test/mdns.test.ts +131 -0
  31. package/extensions/modules/a2a/test/outcome.test.ts +61 -0
  32. package/extensions/modules/a2a/test/persistence.test.ts +92 -0
  33. package/extensions/modules/a2a/test/protocol.test.ts +217 -0
  34. package/extensions/modules/a2a/test/registry.test.ts +114 -0
  35. package/extensions/modules/a2a/test/retry.test.ts +136 -0
  36. package/extensions/modules/a2a/test/security.test.ts +281 -0
  37. package/extensions/modules/a2a/test/server.test.ts +1966 -0
  38. package/extensions/modules/a2a/test/tmp.ts +59 -0
  39. package/extensions/modules/a2a/test/vendor.test.ts +57 -0
  40. package/extensions/modules/a2a/types/bonjour-service.d.ts +22 -0
  41. package/extensions/modules/a2a/vendor/VENDORED.md +18 -0
  42. package/extensions/modules/a2a/vendor/package.json +1 -0
  43. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/LICENSE +23 -0
  44. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.d.ts +14 -0
  45. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.js +57 -0
  46. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.d.ts +4 -0
  47. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.js +3 -0
  48. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.d.ts +13 -0
  49. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.js +50 -0
  50. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.d.ts +41 -0
  51. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.js +209 -0
  52. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.d.ts +9 -0
  53. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.js +42 -0
  54. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.d.ts +14 -0
  55. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.js +119 -0
  56. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.d.ts +14 -0
  57. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.js +142 -0
  58. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.d.ts +7 -0
  59. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.js +53 -0
  60. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.d.ts +58 -0
  61. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.js +130 -0
  62. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.d.ts +1 -0
  63. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.js +13 -0
  64. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.d.ts +1 -0
  65. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.js +17 -0
  66. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.d.ts +4 -0
  67. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.js +22 -0
  68. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.d.ts +3 -0
  69. package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.js +6 -0
  70. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/LICENSE +21 -0
  71. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/classes.js +23 -0
  72. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/index.js +1761 -0
  73. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/opcodes.js +50 -0
  74. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/optioncodes.js +59 -0
  75. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/rcodes.js +50 -0
  76. package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/types.js +103 -0
  77. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/LICENSE +21 -0
  78. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/es6.js +73 -0
  79. package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/index.js +46 -0
  80. package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/LICENSE +21 -0
  81. package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/index.cjs +250 -0
  82. package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/LICENSE +21 -0
  83. package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/index.js +205 -0
  84. package/extensions/modules/a2a/vendor/vendored_deps/thunky/LICENSE +21 -0
  85. package/extensions/modules/a2a/vendor/vendored_deps/thunky/index.js +55 -0
  86. package/extensions/modules/composer/test/module.test.ts +2 -2
  87. package/extensions/modules/config/index.ts +3 -0
  88. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  89. package/extensions/modules/gh/configPanel.ts +82 -0
  90. package/extensions/modules/gh/index.ts +86 -0
  91. package/extensions/modules/gh/lib/gh-cli.ts +337 -0
  92. package/extensions/modules/gh/lib/ops.ts +771 -0
  93. package/extensions/modules/gh/test/gh.test.ts +280 -0
  94. package/extensions/modules/plan/lib/plan-tools.ts +8 -0
  95. package/extensions/modules/repair/index.ts +138 -0
  96. package/extensions/modules/repair/lib/guards.ts +1 -1
  97. package/extensions/modules/repair/lib/read-selector.ts +242 -0
  98. package/extensions/modules/repair/test/read-selector.test.ts +198 -0
  99. package/extensions/modules/steering/configPanel.ts +8 -0
  100. package/extensions/modules/steering/index.ts +6 -0
  101. package/extensions/modules/steering/lib/settings.ts +6 -2
  102. package/extensions/modules/steering/lib/think.ts +66 -0
  103. package/extensions/modules/steering/test/harness.ts +5 -0
  104. package/extensions/modules/steering/test/settings.test.ts +2 -0
  105. package/extensions/modules/steering/test/think.test.ts +77 -0
  106. package/extensions/modules/todo/configPanel.ts +55 -0
  107. package/extensions/modules/todo/index.ts +46 -13
  108. package/extensions/modules/todo/lib/render.ts +271 -0
  109. package/extensions/modules/todo/lib/settings.ts +73 -0
  110. package/extensions/modules/todo/test/todo.test.ts +276 -0
  111. package/extensions/modules/web/index.ts +37 -1
  112. package/extensions/modules/web/lib/a11y.ts +252 -0
  113. package/extensions/modules/web/test/a11y.test.ts +218 -0
  114. package/extensions/modules/web/test/extension.test.ts +2 -2
  115. package/extensions/modules/web/test/hook.test.ts +2 -2
  116. package/extensions/modules/web/vendor/axe/LICENSE +362 -0
  117. package/extensions/modules/web/vendor/axe/LICENSE-3RD-PARTY.txt +66 -0
  118. package/extensions/modules/web/vendor/axe/README.md +19 -0
  119. package/extensions/modules/web/vendor/axe/axe.min.js +12 -0
  120. package/package.json +2 -2
  121. package/skills/a2a/SKILL.md +63 -0
  122. package/skills/web/SKILL.md +1 -0
@@ -0,0 +1,1966 @@
1
+ import { assert } from "./chai.js";
2
+ import * as fs from "node:fs";
3
+ import { createServer, request as httpRequest } from "node:http";
4
+ import * as path from "node:path";
5
+
6
+ import { DEFAULTS } from "./helpers";
7
+ import { makeTempDir } from "./tmp";
8
+ import { A2AServer, type SessionRunner } from "../lib/server";
9
+ import type { A2AConfig } from "../lib/config";
10
+ import { STATE_CANCELED, STATE_COMPLETED, STATE_FAILED, STATE_INPUT_REQUIRED, STATE_REJECTED, STATE_WORKING } from "../lib/protocol";
11
+ import { authenticate } from "../lib/security";
12
+ import { metrics } from "../lib/client";
13
+ import { list as listRegistry } from "../lib/registry";
14
+ import { setGatewayRegistrationName, getGatewayCallerName, gatewayKeyFromUrl } from "../lib/config";
15
+ import { describe, it, before, after, beforeEach, afterEach } from "node:test";
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Stub session runner — returns a canned reply without spawning a real agent.
19
+ // ---------------------------------------------------------------------------
20
+
21
+ function stubRunner(reply = "canned reply"): SessionRunner {
22
+ return async () => ({ reply, inputRequired: false });
23
+ }
24
+
25
+ /** Extract the Task from a v1.0 SendMessageResponse {"task": …} result. */
26
+ function sendTask(r: any): any {
27
+ return r.result?.task;
28
+ }
29
+
30
+ function tmpDir(): string {
31
+ return makeTempDir("pi-a2a-server-");
32
+ }
33
+
34
+ /** Pick an ephemeral free port. */
35
+ async function freePort(): Promise<number> {
36
+ const { createServer } = await import("node:http");
37
+ return new Promise((resolve, reject) => {
38
+ const s = createServer();
39
+ s.listen(0, "127.0.0.1", () => {
40
+ const addr = s.address();
41
+ if (addr && typeof addr === "object") {
42
+ const p = addr.port;
43
+ s.close(() => resolve(p));
44
+ } else {
45
+ reject(new Error("no port"));
46
+ }
47
+ });
48
+ });
49
+ }
50
+
51
+ async function startServer(opts: {
52
+ cfg: A2AConfig;
53
+ runner?: SessionRunner;
54
+ piDir?: string;
55
+ cwd?: string;
56
+ onActivity?: (a: any) => void;
57
+ api?: ConstructorParameters<typeof A2AServer>[0]["api"];
58
+ }): Promise<{
59
+ server: A2AServer;
60
+ url: string;
61
+ stop: () => Promise<void>;
62
+ }> {
63
+ const port = await freePort();
64
+ const cfg = { ...opts.cfg };
65
+ cfg.server = { ...cfg.server, port };
66
+ const piDir = opts.piDir ?? tmpDir();
67
+ const server = new A2AServer({
68
+ cfg,
69
+ cwd: opts.cwd ?? tmpDir(),
70
+ piDir,
71
+ runner: opts.runner ?? stubRunner(),
72
+ api: opts.api,
73
+ onActivity: opts.onActivity,
74
+ });
75
+ const info = await server.start();
76
+ return { server, url: info.url, stop: () => server.stop() };
77
+ }
78
+
79
+ async function jsonRpc(url: string, method: string, params: any, headers: Record<string, string> = {}): Promise<any> {
80
+ const resp = await fetch(url, {
81
+ method: "POST",
82
+ headers: { "Content-Type": "application/json", ...headers },
83
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
84
+ });
85
+ return resp.json();
86
+ }
87
+
88
+ /** Poll tasks/get until the task reaches a terminal state (bounded). */
89
+ async function pollTask(url: string, taskId: string, timeoutMs = 5000): Promise<any> {
90
+ const deadline = Date.now() + timeoutMs;
91
+ for (;;) {
92
+ const r = await jsonRpc(url, "tasks/get", { id: taskId });
93
+ if (r.error) throw new Error(`tasks/get error: ${JSON.stringify(r.error)}`);
94
+ const state = r.result?.status?.state;
95
+ if ([STATE_COMPLETED, STATE_FAILED, STATE_CANCELED, STATE_REJECTED].includes(state)) return r.result;
96
+ if (Date.now() > deadline) throw new Error(`poll timeout; still ${state}`);
97
+ await new Promise((res) => setTimeout(res, 50));
98
+ }
99
+ }
100
+
101
+ describe("server", () => {
102
+ beforeEach(() => metrics.reset());
103
+
104
+ describe("Agent Card", () => {
105
+ it("serves a v1.0 card at the canonical path", async () => {
106
+ const { url, stop } = await startServer({ cfg: DEFAULTS() });
107
+ try {
108
+ const resp = await fetch(url + ".well-known/agent-card.json");
109
+ const card = await resp.json();
110
+ assert.equal(card.version, "1.0.0");
111
+ assert.equal(card.supportedInterfaces[0]?.protocolBinding, "JSONRPC");
112
+ assert.include(card.url, url);
113
+ } finally {
114
+ await stop();
115
+ }
116
+ });
117
+
118
+ it("also serves the legacy agent.json alias", async () => {
119
+ const { url, stop } = await startServer({ cfg: DEFAULTS() });
120
+ try {
121
+ const resp = await fetch(url + ".well-known/agent.json");
122
+ assert.equal(resp.status, 200);
123
+ const card = await resp.json();
124
+ assert.equal(card.version, "1.0.0");
125
+ } finally {
126
+ await stop();
127
+ }
128
+ });
129
+
130
+ it("self-discovers skills from the live session (getCommands) when none configured", async () => {
131
+ const api = {
132
+ getCommands: () => [
133
+ { name: "a2a-config", description: "panel", source: "extension" as const },
134
+ { name: "skill:notebooklm", description: "Google NotebookLM bridge", source: "skill" as const },
135
+ { name: "skill:ponytail", description: "Lazy senior dev mode", source: "skill" as const },
136
+ ],
137
+ };
138
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), api });
139
+ try {
140
+ const card = await (await fetch(url + ".well-known/agent-card.json")).json();
141
+ assert.deepEqual(
142
+ card.skills.map((s: any) => s.id),
143
+ ["notebooklm", "ponytail"],
144
+ );
145
+ assert.equal(card.skills[0].description, "Google NotebookLM bridge");
146
+ } finally {
147
+ await stop();
148
+ }
149
+ });
150
+
151
+ it("falls back to the default coding skill when no skills are discoverable", async () => {
152
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), api: {} });
153
+ try {
154
+ const card = await (await fetch(url + ".well-known/agent-card.json")).json();
155
+ assert.equal(card.skills.length, 1);
156
+ assert.equal(card.skills[0].id, "coding");
157
+ } finally {
158
+ await stop();
159
+ }
160
+ });
161
+
162
+ it("explicit server.skills config wins over discovery (backward compat)", async () => {
163
+ const cfg = DEFAULTS();
164
+ cfg.server.skills = [{ id: "custom", name: "custom", description: "configured" }];
165
+ const api = {
166
+ getCommands: () => [{ name: "skill:notebooklm", description: "discovered", source: "skill" as const }],
167
+ };
168
+ const { url, stop } = await startServer({ cfg, api });
169
+ try {
170
+ const card = await (await fetch(url + ".well-known/agent-card.json")).json();
171
+ assert.equal(card.skills.length, 1);
172
+ assert.equal(card.skills[0].id, "custom");
173
+ } finally {
174
+ await stop();
175
+ }
176
+ });
177
+
178
+ it("falls back to the coding skill when getCommands() throws", async () => {
179
+ const api = { getCommands: () => { throw new Error("boom"); } };
180
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), api });
181
+ try {
182
+ const card = await (await fetch(url + ".well-known/agent-card.json")).json();
183
+ assert.equal(card.skills.length, 1);
184
+ assert.equal(card.skills[0].id, "coding");
185
+ } finally {
186
+ await stop();
187
+ }
188
+ });
189
+
190
+ it("caps discovered skill descriptions at 1024 chars", async () => {
191
+ const api = {
192
+ getCommands: () => [{ name: "skill:big", description: "x".repeat(2000), source: "skill" as const }],
193
+ };
194
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), api });
195
+ try {
196
+ const card = await (await fetch(url + ".well-known/agent-card.json")).json();
197
+ assert.equal(card.skills[0].description.length, 1024);
198
+ } finally {
199
+ await stop();
200
+ }
201
+ });
202
+
203
+ it("#9: strips enriched session metadata from the card for anonymous (unauthenticated) callers", async () => {
204
+ const cfg = DEFAULTS();
205
+ cfg.server.sharedToken = "test-shared-token";
206
+ const { url, stop } = await startServer({ cfg });
207
+ try {
208
+ // Anonymous (no Authorization header) → plain card, no metadata.
209
+ const anon = await (await fetch(url + ".well-known/agent-card.json")).json();
210
+ assert.equal(anon.metadata, undefined);
211
+ assert.equal(anon.capabilities.extensions, undefined);
212
+ // Authenticated → enriched card with pi-session metadata.
213
+ const auth = await (await fetch(url + ".well-known/agent-card.json", {
214
+ headers: { Authorization: "Bearer test-shared-token" },
215
+ })).json();
216
+ assert.notEqual(auth.metadata, undefined);
217
+ assert.equal(auth.metadata.extension, "https://bacnh85.dev/a2a/extensions/pi-session/v1");
218
+ } finally {
219
+ await stop();
220
+ }
221
+ });
222
+
223
+ it("#9: anonymous card withholds discovered skills (configured skills stay public)", async () => {
224
+ const cfg = DEFAULTS();
225
+ cfg.server.sharedToken = "test-shared-token";
226
+ const api = {
227
+ getCommands: () => [{ name: "skill:notebooklm", description: "Google NotebookLM bridge", source: "skill" as const }],
228
+ };
229
+ const { url, stop } = await startServer({ cfg, api });
230
+ try {
231
+ // Anonymous → coding fallback only; local skill names are not disclosed.
232
+ const anon = await (await fetch(url + ".well-known/agent-card.json")).json();
233
+ assert.equal(anon.skills.length, 1);
234
+ assert.equal(anon.skills[0].id, "coding");
235
+ // Authenticated → full discovered list.
236
+ const auth = await (await fetch(url + ".well-known/agent-card.json", {
237
+ headers: { Authorization: "Bearer test-shared-token" },
238
+ })).json();
239
+ assert.deepEqual(auth.skills.map((s: any) => s.id), ["notebooklm"]);
240
+ } finally {
241
+ await stop();
242
+ }
243
+ });
244
+
245
+ it("#9: anonymous card still serves explicitly configured skills", async () => {
246
+ const cfg = DEFAULTS();
247
+ cfg.server.sharedToken = "test-shared-token";
248
+ cfg.server.skills = [{ id: "custom", name: "custom", description: "configured" }];
249
+ const api = {
250
+ getCommands: () => [{ name: "skill:notebooklm", description: "discovered", source: "skill" as const }],
251
+ };
252
+ const { url, stop } = await startServer({ cfg, api });
253
+ try {
254
+ // Configured skills are opt-in public (pre-0.6.3 semantics) — served
255
+ // even to anonymous callers, ahead of the anonymous-withholding guard.
256
+ const anon = await (await fetch(url + ".well-known/agent-card.json")).json();
257
+ assert.equal(anon.skills.length, 1);
258
+ assert.equal(anon.skills[0].id, "custom");
259
+ } finally {
260
+ await stop();
261
+ }
262
+ });
263
+
264
+ it("#9: /metrics requires authentication", async () => {
265
+ const cfg = DEFAULTS();
266
+ cfg.server.sharedToken = "test-shared-token";
267
+ const { url, stop } = await startServer({ cfg });
268
+ try {
269
+ const anon = await fetch(url + "metrics");
270
+ assert.equal(anon.status, 401);
271
+ const auth = await fetch(url + "metrics", {
272
+ headers: { Authorization: "Bearer test-shared-token" },
273
+ });
274
+ assert.equal(auth.status, 200);
275
+ } finally {
276
+ await stop();
277
+ }
278
+ });
279
+ });
280
+
281
+ describe("session discovery (0.2.0)", () => {
282
+ it("registers itself in the local file registry on start", async () => {
283
+ const piDir = tmpDir();
284
+ const cwd = "/test-repo";
285
+ const { server, stop } = await startServer({ cfg: DEFAULTS(), piDir, cwd });
286
+ try {
287
+ // The server uses process.pid as the registry key — which is alive.
288
+ const entries = listRegistry({ piDir, ttlSec: 60 });
289
+ const self = entries.find((e) => e.pid === process.pid);
290
+ assert.isOk(self, "server should have registered its own pid");
291
+ assert.equal(self!.cwd, cwd);
292
+ assert.equal(self!.port, server.port);
293
+ } finally {
294
+ await stop();
295
+ }
296
+ });
297
+
298
+ it("defaults agentName to hostname-port so same-machine sessions don't collide", async () => {
299
+ const piDir = tmpDir();
300
+ const { server, stop } = await startServer({ cfg: DEFAULTS(), piDir });
301
+ try {
302
+ const self = listRegistry({ piDir, ttlSec: 60 }).find((e) => e.pid === process.pid);
303
+ assert.isOk(self);
304
+ assert.include(self!.agentName, `-${server.port}`, "unpinned name must carry the bound port");
305
+ } finally {
306
+ await stop();
307
+ }
308
+ });
309
+
310
+ it("keeps a pinned agentName verbatim (no port suffix)", async () => {
311
+ const piDir = tmpDir();
312
+ const cfg = DEFAULTS();
313
+ cfg.server.agentName = "my-pinned";
314
+ const { stop } = await startServer({ cfg, piDir });
315
+ try {
316
+ const self = listRegistry({ piDir, ttlSec: 60 }).find((e) => e.pid === process.pid);
317
+ assert.isOk(self);
318
+ assert.equal(self!.agentName, "my-pinned");
319
+ } finally {
320
+ await stop();
321
+ }
322
+ });
323
+
324
+ it("name getter matches the registered local-registry name", async () => {
325
+ const piDir = tmpDir();
326
+ const { server, stop } = await startServer({ cfg: DEFAULTS(), piDir });
327
+ try {
328
+ const self = listRegistry({ piDir, ttlSec: 60 }).find((e) => e.pid === process.pid);
329
+ assert.isOk(self);
330
+ assert.equal(server.name, self!.agentName);
331
+ } finally {
332
+ await stop();
333
+ }
334
+ });
335
+
336
+ it("unregisters from the registry on stop", async () => {
337
+ const piDir = tmpDir();
338
+ const { stop } = await startServer({ cfg: DEFAULTS(), piDir });
339
+ await stop();
340
+ const entries = listRegistry({ piDir, ttlSec: 60 });
341
+ const self = entries.find((e) => e.pid === process.pid);
342
+ assert.isUndefined(self, "registry entry should be removed on stop");
343
+ });
344
+
345
+ it("enriches the Agent Card with session metadata when enrichCard is on", async () => {
346
+ const cfg = DEFAULTS();
347
+ const cwd = "/enriched-repo";
348
+ const { url, stop } = await startServer({ cfg, cwd });
349
+ try {
350
+ const resp = await fetch(url + ".well-known/agent-card.json");
351
+ const card = await resp.json();
352
+ assert.isDefined(card.capabilities.extensions, "card should declare the extension");
353
+ assert.isDefined(card.metadata, "card should carry metadata");
354
+ assert.equal(card.metadata.cwd, cwd);
355
+ assert.equal(card.metadata.pid, process.pid);
356
+ } finally {
357
+ await stop();
358
+ }
359
+ });
360
+
361
+ it("omits metadata from the card when enrichCard is off", async () => {
362
+ const cfg = DEFAULTS();
363
+ cfg.discovery.enrichCard = false;
364
+ const { url, stop } = await startServer({ cfg });
365
+ try {
366
+ const resp = await fetch(url + ".well-known/agent-card.json");
367
+ const card = await resp.json();
368
+ assert.isUndefined(card.metadata);
369
+ assert.isUndefined(card.capabilities.extensions);
370
+ } finally {
371
+ await stop();
372
+ }
373
+ });
374
+
375
+ it("does NOT write a registry file when local discovery is disabled", async () => {
376
+ const cfg = DEFAULTS();
377
+ cfg.discovery.local.enabled = false;
378
+ const piDir = tmpDir();
379
+ const { stop } = await startServer({ cfg, piDir });
380
+ try {
381
+ const entries = listRegistry({ piDir, ttlSec: 60 });
382
+ assert.lengthOf(entries, 0, "no registry file should be written");
383
+ } finally {
384
+ await stop();
385
+ }
386
+ });
387
+ });
388
+
389
+ describe("auth gate", () => {
390
+ it("passes in localhost-only mode (no token)", async () => {
391
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("ok") });
392
+ try {
393
+ const r = await jsonRpc(url, "SendMessage", {
394
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
395
+ });
396
+ assert.isUndefined(r.error, "no auth error");
397
+ assert.equal(sendTask(r).status.state, STATE_COMPLETED);
398
+ } finally {
399
+ await stop();
400
+ }
401
+ });
402
+
403
+ it("rejects 401 when a token is set but not presented", async () => {
404
+ const cfg = DEFAULTS();
405
+ cfg.server.sharedToken = "secret";
406
+ const { url, stop } = await startServer({ cfg, runner: stubRunner("ok") });
407
+ try {
408
+ const r = await jsonRpc(url, "SendMessage", {
409
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
410
+ });
411
+ assert.equal(r.error?.code, -32050, "unauthorized");
412
+ } finally {
413
+ await stop();
414
+ }
415
+ });
416
+
417
+ it("accepts the correct token", async () => {
418
+ const cfg = DEFAULTS();
419
+ cfg.server.sharedToken = "secret";
420
+ const { url, stop } = await startServer({ cfg, runner: stubRunner("ok") });
421
+ try {
422
+ const r = await jsonRpc(
423
+ url,
424
+ "SendMessage",
425
+ { message: { role: "ROLE_USER", parts: [{ text: "hi" }] } },
426
+ { Authorization: "Bearer secret" },
427
+ );
428
+ assert.isUndefined(r.error);
429
+ assert.equal(sendTask(r).status.state, STATE_COMPLETED);
430
+ } finally {
431
+ await stop();
432
+ }
433
+ });
434
+
435
+ it("rejects a non-loopback Host in localhost-only mode (DNS-rebinding guard)", async () => {
436
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("ok") });
437
+ try {
438
+ // Node's fetch() forbids the Host header, so use raw http.request —
439
+ // this is exactly how a DNS-rebinding attack presents itself.
440
+ const status = await new Promise<number>((resolve, reject) => {
441
+ const req = httpRequest(url, {
442
+ method: "POST",
443
+ headers: {
444
+ "Content-Type": "application/json",
445
+ Host: "evil.example.com", // attacker domain resolving to 127.0.0.1
446
+ },
447
+ }, (res) => {
448
+ res.resume();
449
+ resolve(res.statusCode ?? 0);
450
+ });
451
+ req.on("error", reject);
452
+ req.end(JSON.stringify({
453
+ jsonrpc: "2.0",
454
+ id: 1,
455
+ method: "SendMessage",
456
+ params: { message: { role: "ROLE_USER", parts: [{ text: "hi" }] } },
457
+ }));
458
+ });
459
+ assert.equal(status, 403, "non-loopback Host must be rejected");
460
+ } finally {
461
+ await stop();
462
+ }
463
+ });
464
+
465
+ it("rejects a non-loopback Origin (CSRF guard)", async () => {
466
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("ok") });
467
+ try {
468
+ const resp = await fetch(url, {
469
+ method: "POST",
470
+ headers: {
471
+ "Content-Type": "application/json",
472
+ Origin: "https://evil.example.com",
473
+ },
474
+ body: JSON.stringify({
475
+ jsonrpc: "2.0",
476
+ id: 1,
477
+ method: "SendMessage",
478
+ params: { message: { role: "ROLE_USER", parts: [{ text: "hi" }] } },
479
+ }),
480
+ });
481
+ assert.equal(resp.status, 403, "non-loopback Origin must be rejected");
482
+ } finally {
483
+ await stop();
484
+ }
485
+ });
486
+
487
+ it("rejects browser simple-request content-types (text/plain CSRF body)", async () => {
488
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("ok") });
489
+ try {
490
+ const resp = await fetch(url, {
491
+ method: "POST",
492
+ headers: { "Content-Type": "text/plain;charset=UTF-8" },
493
+ body: JSON.stringify({
494
+ jsonrpc: "2.0",
495
+ id: 1,
496
+ method: "SendMessage",
497
+ params: { message: { role: "ROLE_USER", parts: [{ text: "hi" }] } },
498
+ }),
499
+ });
500
+ assert.equal(resp.status, 415, "text/plain must be rejected");
501
+ } finally {
502
+ await stop();
503
+ }
504
+ });
505
+
506
+ it("accepts a bracketed IPv6 loopback Host [::1] (no false-positive 403)", async () => {
507
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("ok") });
508
+ try {
509
+ // Server binds 127.0.0.1; we send a bracketed-IPv6 Host header over that
510
+ // connection — this exercises the header parser, exactly where the old
511
+ // split(":")[0] bug lived ([::1]:port → "[" → false 403).
512
+ const status = await new Promise<number>((resolve, reject) => {
513
+ const u = new URL(url);
514
+ const req = httpRequest(
515
+ {
516
+ host: "127.0.0.1",
517
+ port: u.port,
518
+ method: "POST",
519
+ path: "/",
520
+ headers: { "Content-Type": "application/json", Host: `[::1]:${u.port}` },
521
+ },
522
+ (res) => {
523
+ res.resume();
524
+ resolve(res.statusCode ?? 0);
525
+ },
526
+ );
527
+ req.on("error", reject);
528
+ req.end(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "SendMessage", params: { message: { role: "ROLE_USER", parts: [{ text: "hi" }] } } }));
529
+ });
530
+ assert.equal(status, 200, "[::1]:port Host must be recognized as loopback, not 403");
531
+ } finally {
532
+ await stop();
533
+ }
534
+ });
535
+
536
+ it("applies the Host gate to GET requests too (agent card via rebinding domain → 403)", async () => {
537
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("ok") });
538
+ try {
539
+ const status = await new Promise<number>((resolve, reject) => {
540
+ const u = new URL(url);
541
+ const req = httpRequest(
542
+ { host: "127.0.0.1", port: u.port, method: "GET", path: "/.well-known/agent-card.json", headers: { Host: "evil.example.com" } },
543
+ (res) => {
544
+ res.resume();
545
+ resolve(res.statusCode ?? 0);
546
+ },
547
+ );
548
+ req.on("error", reject);
549
+ req.end();
550
+ });
551
+ assert.equal(status, 403, "GET with non-loopback Host must be rejected");
552
+ } finally {
553
+ await stop();
554
+ }
555
+ });
556
+
557
+ it("rejects Origin: null (sandboxed iframe) with 403", async () => {
558
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("ok") });
559
+ try {
560
+ const resp = await fetch(url, {
561
+ method: "POST",
562
+ headers: { "Content-Type": "application/json", Origin: "null" },
563
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "SendMessage", params: { message: { role: "ROLE_USER", parts: [{ text: "hi" }] } } }),
564
+ });
565
+ assert.equal(resp.status, 403, "Origin: null must be rejected");
566
+ } finally {
567
+ await stop();
568
+ }
569
+ });
570
+
571
+ it("keeps working with application/json + loopback Host/Origin (no regression)", async () => {
572
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("ok") });
573
+ try {
574
+ const r = await jsonRpc(url, "SendMessage", {
575
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
576
+ });
577
+ assert.isUndefined(r.error, "loopback request must still pass");
578
+ assert.equal(sendTask(r).status.state, STATE_COMPLETED);
579
+ } finally {
580
+ await stop();
581
+ }
582
+ });
583
+ });
584
+
585
+ describe("outbound reply redaction", () => {
586
+ it("redacts credential-shaped strings from the reply artifact", async () => {
587
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("key is sk-test-abcdEFGH01234567JKLM and ghp_ABCDEFGHIJKLMNOPQRST and mytest@example.com") });
588
+ try {
589
+ const r = await jsonRpc(url, "SendMessage", {
590
+ message: { role: "ROLE_USER", parts: [{ text: "show secrets" }] },
591
+ });
592
+ const text = sendTask(r).artifacts?.[0]?.parts?.[0]?.text ?? "";
593
+ assert.notInclude(text, "sk-test-abcdEFGH01234567JKLM", "sk-* must be redacted");
594
+ assert.notInclude(text, "ghp_ABCDEFGHIJKLMNOPQRST", "ghp_* must be redacted");
595
+ assert.notInclude(text, "mytest@example.com", "email must be redacted");
596
+ assert.include(text, "[redacted]", "redaction placeholder present");
597
+ } finally {
598
+ await stop();
599
+ }
600
+ });
601
+
602
+ it("leaves plain replies unchanged (no over-redaction)", async () => {
603
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("hello world") });
604
+ try {
605
+ const r = await jsonRpc(url, "SendMessage", {
606
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
607
+ });
608
+ const text = sendTask(r).artifacts?.[0]?.parts?.[0]?.text ?? "";
609
+ assert.equal(text, "hello world");
610
+ } finally {
611
+ await stop();
612
+ }
613
+ });
614
+
615
+ it("redacts the failure message too (error text can embed reply content)", async () => {
616
+ // Runner throws an error whose message embeds a credential-shaped string —
617
+ // the FAILED task's status.message must be scrubbed before tasks/get or
618
+ // SSE returns it to a peer.
619
+ const runner: SessionRunner = async () => {
620
+ throw new Error("tool failed: token sk-abcdEFGHIJKL0123456789 leaked in payload");
621
+ };
622
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner });
623
+ try {
624
+ const r = await jsonRpc(url, "SendMessage", {
625
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
626
+ });
627
+ assert.equal(sendTask(r).status.state, STATE_FAILED);
628
+ const msg = sendTask(r).status.message?.parts?.[0]?.text ?? "";
629
+ assert.notInclude(msg, "sk-abcdEFGHIJKL0123456789", "failure message must be redacted");
630
+ assert.include(msg, "[redacted]", "redaction placeholder present");
631
+ } finally {
632
+ await stop();
633
+ }
634
+ });
635
+ });
636
+
637
+ describe("task lifecycle", () => {
638
+ it("runs the session and returns a COMPLETED task with the reply artifact", async () => {
639
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("the real reply") });
640
+ try {
641
+ const r = await jsonRpc(url, "SendMessage", {
642
+ message: { role: "ROLE_USER", parts: [{ text: "do something" }] },
643
+ });
644
+ const task = sendTask(r);
645
+ assert.equal(task.status.state, STATE_COMPLETED);
646
+ assert.deepEqual(task.artifacts?.[0]?.parts?.[0], { text: "the real reply", mediaType: "text/plain" });
647
+ assert.match(task.id, /^task-/);
648
+ assert.match(task.contextId, /^ctx-/);
649
+ } finally {
650
+ await stop();
651
+ }
652
+ });
653
+
654
+ it("maps an INPUT_REQUIRED reply", async () => {
655
+ const runner: SessionRunner = async () => ({ reply: "what exactly?", inputRequired: true });
656
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner });
657
+ try {
658
+ const r = await jsonRpc(url, "SendMessage", {
659
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
660
+ });
661
+ assert.equal(sendTask(r).status.state, STATE_INPUT_REQUIRED);
662
+ } finally {
663
+ await stop();
664
+ }
665
+ });
666
+
667
+ it("accepts the pre-1.0 message/send alias", async () => {
668
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("legacy ok") });
669
+ try {
670
+ const r = await jsonRpc(url, "message/send", {
671
+ message: { role: "user", parts: [{ text: "hi", mediaType: "text/plain" }] },
672
+ });
673
+ assert.equal(r.result.status.state, STATE_COMPLETED);
674
+ } finally {
675
+ await stop();
676
+ }
677
+ });
678
+
679
+ it("tasks/get retrieves a created task, tasks/list lists them", async () => {
680
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("x") });
681
+ try {
682
+ const send = await jsonRpc(url, "SendMessage", {
683
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
684
+ });
685
+ const tid = sendTask(send).id;
686
+ const got = await jsonRpc(url, "tasks/get", { id: tid });
687
+ assert.equal(got.result.id, tid);
688
+ const list = await jsonRpc(url, "tasks/list", {});
689
+ assert.isAtLeast(list.result.tasks.length, 1);
690
+ } finally {
691
+ await stop();
692
+ }
693
+ });
694
+
695
+ it("tasks/get on an unknown id returns TaskNotFoundError", async () => {
696
+ const { url, stop } = await startServer({ cfg: DEFAULTS() });
697
+ try {
698
+ const r = await jsonRpc(url, "tasks/get", { id: "nope" });
699
+ assert.equal(r.error?.code, -32001);
700
+ } finally {
701
+ await stop();
702
+ }
703
+ });
704
+ });
705
+
706
+ describe("inbound activity (0.3.0)", () => {
707
+ it("emits arrived → progress → completed for a successful task", async () => {
708
+ const events: any[] = [];
709
+ const runner: SessionRunner = async ({ onProgress }) => {
710
+ onProgress?.("⚙ bash npm test");
711
+ return { reply: "all good", inputRequired: false };
712
+ };
713
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner, onActivity: (a) => events.push(a) });
714
+ try {
715
+ await jsonRpc(url, "SendMessage", {
716
+ message: { role: "ROLE_USER", parts: [{ text: "run tests" }] },
717
+ });
718
+ const types = events.map((e) => e.type);
719
+ assert.deepEqual(types, ["arrived", "progress", "completed"]);
720
+ assert.equal(events[0]!.identity, "ip:127.0.0.1"); // localhost-only mode
721
+ assert.match(events[0]!.text, /run tests/);
722
+ assert.match(events[1]!.line, /npm test/);
723
+ assert.match(events[2]!.replyPreview, /all good/);
724
+ assert.equal(events[2]!.state, STATE_COMPLETED);
725
+ } finally {
726
+ await stop();
727
+ }
728
+ });
729
+
730
+ it("emits failed with the error when the runner throws", async () => {
731
+ const events: any[] = [];
732
+ const runner: SessionRunner = async () => {
733
+ throw new Error("kaboom");
734
+ };
735
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner, onActivity: (a) => events.push(a) });
736
+ try {
737
+ await jsonRpc(url, "SendMessage", {
738
+ message: { role: "ROLE_USER", parts: [{ text: "boom" }] },
739
+ });
740
+ const types = events.map((e) => e.type);
741
+ assert.deepEqual(types, ["arrived", "failed"]);
742
+ assert.match(events[1]!.error, /kaboom/);
743
+ } finally {
744
+ await stop();
745
+ }
746
+ });
747
+
748
+ it("emits completed (canceled) for a user cancel", async () => {
749
+ const events: any[] = [];
750
+ let release!: () => void;
751
+ const gate = new Promise<void>((r) => (release = r));
752
+ const runner: SessionRunner = async ({ signal }) => {
753
+ await new Promise<void>((resolve, reject) => {
754
+ const onAbort = () => reject(new Error("aborted"));
755
+ signal.addEventListener("abort", onAbort, { once: true });
756
+ void gate.then(() => {
757
+ signal.removeEventListener("abort", onAbort);
758
+ resolve();
759
+ });
760
+ });
761
+ return { reply: "never", inputRequired: false };
762
+ };
763
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner, onActivity: (a) => events.push(a) });
764
+ try {
765
+ const sendP = jsonRpc(url, "SendMessage", {
766
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
767
+ });
768
+ // Let the task start, then cancel it.
769
+ await new Promise((r) => setTimeout(r, 50));
770
+ const tasks = await jsonRpc(url, "tasks/list", {});
771
+ const tid = tasks.result.tasks[0]!.id;
772
+ await jsonRpc(url, "tasks/cancel", { id: tid });
773
+ await sendP;
774
+ const types = events.map((e) => e.type);
775
+ assert.deepEqual(types, ["arrived", "completed"]);
776
+ assert.equal(events[1]!.state, STATE_CANCELED);
777
+ } finally {
778
+ release();
779
+ await stop();
780
+ }
781
+ });
782
+
783
+ it("does not crash without an onActivity handler (backward compat)", async () => {
784
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("ok") });
785
+ try {
786
+ const r = await jsonRpc(url, "SendMessage", {
787
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
788
+ });
789
+ assert.equal(sendTask(r).status.state, STATE_COMPLETED);
790
+ } finally {
791
+ await stop();
792
+ }
793
+ });
794
+ });
795
+
796
+ describe("anti-loop", () => {
797
+ it("rejects after the per-context turn cap", async () => {
798
+ const cfg = DEFAULTS();
799
+ cfg.server.maxPingpongTurns = 2;
800
+ const { url, stop } = await startServer({ cfg, runner: stubRunner("ok") });
801
+ try {
802
+ // Send twice with the same contextId — allowed.
803
+ const r1 = await jsonRpc(url, "SendMessage", {
804
+ message: { role: "ROLE_USER", parts: [{ text: "t1" }], contextId: "ctx-loop" },
805
+ });
806
+ assert.equal(sendTask(r1).status.state, STATE_COMPLETED);
807
+ const r2 = await jsonRpc(url, "SendMessage", {
808
+ message: { role: "ROLE_USER", parts: [{ text: "t2" }], contextId: "ctx-loop" },
809
+ });
810
+ assert.equal(sendTask(r2).status.state, STATE_COMPLETED);
811
+ // Third — rejected.
812
+ const r3 = await jsonRpc(url, "SendMessage", {
813
+ message: { role: "ROLE_USER", parts: [{ text: "t3" }], contextId: "ctx-loop" },
814
+ });
815
+ assert.equal(sendTask(r3).status.state, STATE_REJECTED);
816
+ } finally {
817
+ await stop();
818
+ }
819
+ });
820
+ });
821
+
822
+ describe("tasks/cancel on a running task", () => {
823
+ it("cancels a running task and sets STATE_CANCELED", async () => {
824
+ // A runner that blocks until aborted.
825
+ const runner: SessionRunner = ({ signal }) =>
826
+ new Promise((resolve, reject) => {
827
+ signal.addEventListener("abort", () => reject(new Error("aborted")));
828
+ });
829
+ const { server, url, stop } = await startServer({ cfg: DEFAULTS(), runner });
830
+ try {
831
+ // Start the task (don't await — it blocks).
832
+ const sendP = jsonRpc(url, "SendMessage", {
833
+ message: { role: "ROLE_USER", parts: [{ text: "long task" }] },
834
+ });
835
+ // Wait for it to register.
836
+ await new Promise((r) => setTimeout(r, 150));
837
+ // Cancel it.
838
+ const list = await jsonRpc(url, "tasks/list", {});
839
+ const tid = list.result.tasks[0].id;
840
+ const cancel = await jsonRpc(url, "tasks/cancel", { id: tid });
841
+ assert.equal(cancel.result.status.state, STATE_CANCELED);
842
+ // The original send resolves to a CANCELED task too.
843
+ const send = await sendP;
844
+ assert.equal(sendTask(send).status.state, STATE_CANCELED);
845
+ } finally {
846
+ await stop();
847
+ }
848
+ });
849
+
850
+ it("returns TaskNotCancelable on a completed task", async () => {
851
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("done") });
852
+ try {
853
+ const send = await jsonRpc(url, "SendMessage", {
854
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
855
+ });
856
+ const tid = sendTask(send).id;
857
+ const cancel = await jsonRpc(url, "tasks/cancel", { id: tid });
858
+ assert.equal(cancel.error?.code, -32002);
859
+ } finally {
860
+ await stop();
861
+ }
862
+ });
863
+
864
+ it("#10: tasks are per-identity — another peer cannot get/list/cancel them", async () => {
865
+ const cfg = DEFAULTS();
866
+ cfg.server.peerTokens = { alice: "tok-alice", bob: "tok-bob" };
867
+ const { url, stop } = await startServer({ cfg, runner: stubRunner("secret result") });
868
+ const aliceH = { Authorization: "Bearer tok-alice" };
869
+ const bobH = { Authorization: "Bearer tok-bob" };
870
+ try {
871
+ const send = await jsonRpc(url, "SendMessage", {
872
+ message: { role: "ROLE_USER", parts: [{ text: "alice task" }] },
873
+ }, aliceH);
874
+ const tid = sendTask(send).id;
875
+ // Bob cannot fetch Alice's task or see it in his list.
876
+ const foreignGet = await jsonRpc(url, "tasks/get", { id: tid }, bobH);
877
+ assert.equal(foreignGet.error?.code, -32001, "foreign tasks/get must fail");
878
+ const bobList = await jsonRpc(url, "tasks/list", {}, bobH);
879
+ assert.equal(bobList.result.tasks.length, 0, "tasks/list must only show own tasks");
880
+ const foreignCancel = await jsonRpc(url, "tasks/cancel", { id: tid }, bobH);
881
+ assert.equal(foreignCancel.error?.code, -32001, "foreign tasks/cancel must fail");
882
+ // Alice still can.
883
+ const ownGet = await jsonRpc(url, "tasks/get", { id: tid }, aliceH);
884
+ assert.equal(ownGet.result.id, tid);
885
+ const aliceList = await jsonRpc(url, "tasks/list", {}, aliceH);
886
+ assert.equal(aliceList.result.tasks.length, 1);
887
+ } finally {
888
+ await stop();
889
+ }
890
+ });
891
+ });
892
+
893
+ describe("maxConcurrent enforcement", () => {
894
+ it("rejects with 503 when concurrency is exceeded", async () => {
895
+ const runner: SessionRunner = ({ signal }) =>
896
+ new Promise((_resolve, reject) => {
897
+ signal.addEventListener("abort", () => reject(new Error("aborted")));
898
+ });
899
+ const cfg = DEFAULTS();
900
+ cfg.server.maxConcurrent = 1;
901
+ const { server, url, stop } = await startServer({ cfg, runner });
902
+ try {
903
+ // Start one blocking task (don't await).
904
+ // node:test converts a floating fetch's post-stop rejection into an
905
+ // unhandledRejection (mocha swallowed it) — attach the swallow.
906
+ jsonRpc(url, "SendMessage", {
907
+ message: { role: "ROLE_USER", parts: [{ text: "block" }] },
908
+ }).catch(() => {});
909
+ await new Promise((r) => setTimeout(r, 150));
910
+ assert.equal(server.runningCount, 1);
911
+ // Second concurrent task should be rejected.
912
+ const r2 = await jsonRpc(url, "SendMessage", {
913
+ message: { role: "ROLE_USER", parts: [{ text: "second" }] },
914
+ });
915
+ assert.equal(r2.error?.code, -32053);
916
+ assert.include(r2.error?.message ?? "", "busy");
917
+ } finally {
918
+ await stop();
919
+ }
920
+ });
921
+
922
+ it("also enforces the cap on message/stream (no bypass)", async () => {
923
+ const runner: SessionRunner = ({ signal }) =>
924
+ new Promise((_resolve, reject) => {
925
+ signal.addEventListener("abort", () => reject(new Error("aborted")));
926
+ });
927
+ const cfg = DEFAULTS();
928
+ cfg.server.maxConcurrent = 1;
929
+ const { server, url, stop } = await startServer({ cfg, runner });
930
+ try {
931
+ // Start one blocking streaming task (don't await).
932
+ fetch(url, {
933
+ method: "POST",
934
+ headers: { "Content-Type": "application/json" },
935
+ body: JSON.stringify({
936
+ jsonrpc: "2.0",
937
+ id: "s1",
938
+ method: "message/stream",
939
+ params: { message: { role: "ROLE_USER", parts: [{ text: "block" }] } },
940
+ }),
941
+ }).catch(() => {});
942
+ await new Promise((r) => setTimeout(r, 200));
943
+ assert.equal(server.runningCount, 1);
944
+ // A second message/stream should receive a busy error frame.
945
+ const resp = await fetch(url, {
946
+ method: "POST",
947
+ headers: { "Content-Type": "application/json" },
948
+ body: JSON.stringify({
949
+ jsonrpc: "2.0",
950
+ id: "s2",
951
+ method: "message/stream",
952
+ params: { message: { role: "ROLE_USER", parts: [{ text: "second" }] } },
953
+ }),
954
+ });
955
+ const text = await resp.text();
956
+ const frames = text.split("\n").filter((l) => l.startsWith("data:")).map((l) => JSON.parse(l.replace(/^data:\s*/, "")));
957
+ const errFrame = frames.find((f) => f.error);
958
+ assert.exists(errFrame, "expected a busy error frame");
959
+ assert.equal(errFrame.error.code, -32053);
960
+ } finally {
961
+ await stop();
962
+ }
963
+ });
964
+ });
965
+
966
+ describe("message/stream SSE framing", () => {
967
+ it("emits JSON-RPC-enveloped SSE frames echoing the request id", async () => {
968
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("streamed reply") });
969
+ try {
970
+ const resp = await fetch(url, {
971
+ method: "POST",
972
+ headers: { "Content-Type": "application/json" },
973
+ body: JSON.stringify({
974
+ jsonrpc: "2.0",
975
+ id: "sse-1",
976
+ method: "message/stream",
977
+ params: { message: { role: "ROLE_USER", parts: [{ text: "hi" }] } },
978
+ }),
979
+ });
980
+ const text = await resp.text();
981
+ // Parse each data: line.
982
+ const frames = text
983
+ .split("\n")
984
+ .filter((l) => l.startsWith("data:"))
985
+ .map((l) => JSON.parse(l.replace(/^data:\s*/, "")));
986
+ assert.isAtLeast(frames.length, 1, "at least one SSE frame");
987
+ // Every frame must be a JSON-RPC 2.0 response with the echoed id.
988
+ for (const f of frames) {
989
+ assert.equal(f.jsonrpc, "2.0");
990
+ assert.equal(f.id, "sse-1");
991
+ assert.exists(f.result, "frame must have a result");
992
+ }
993
+ // The final statusUpdate must carry the completed task.
994
+ const statusFrame = frames.find((f) => f.result?.statusUpdate);
995
+ assert.equal(statusFrame?.result?.statusUpdate?.status?.state, STATE_COMPLETED);
996
+ } finally {
997
+ await stop();
998
+ }
999
+ });
1000
+ });
1001
+
1002
+ describe("v1.0 wire shapes (PascalCase methods)", () => {
1003
+ /** POST one JSON-RPC frame and return the parsed SSE data frames. */
1004
+ async function sseFrames(url: string, method: string, params: any, id = "sse-v1"): Promise<any[]> {
1005
+ const resp = await fetch(url, {
1006
+ method: "POST",
1007
+ headers: { "Content-Type": "application/json" },
1008
+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
1009
+ });
1010
+ const text = await resp.text();
1011
+ return text
1012
+ .split("\n")
1013
+ .filter((l) => l.startsWith("data:"))
1014
+ .map((l) => JSON.parse(l.replace(/^data:\s*/, "")));
1015
+ }
1016
+
1017
+ it("SendMessage returns the oneof {\"task\": …} wrapper, not a bare Task", async () => {
1018
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("wrapped reply") });
1019
+ try {
1020
+ const r = await jsonRpc(url, "SendMessage", {
1021
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
1022
+ });
1023
+ assert.isUndefined(r.error);
1024
+ // The result must be the oneof wrapper with exactly the task member.
1025
+ assert.exists(r.result?.task, "result must carry {task: …}");
1026
+ assert.notExists(r.result?.message);
1027
+ assert.equal(r.result.task.status.state, STATE_COMPLETED);
1028
+ assert.equal(r.result.task.artifacts?.[0]?.parts?.[0]?.text, "wrapped reply");
1029
+ // …and must not leak Task fields at the top level.
1030
+ assert.isUndefined(r.result.status, "bare Task shape must not bleed through");
1031
+ } finally {
1032
+ await stop();
1033
+ }
1034
+ });
1035
+
1036
+ it("SendStreamingMessage emits TaskArtifactUpdateEvent then a final TaskStatusUpdateEvent", async () => {
1037
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("stream body") });
1038
+ try {
1039
+ const frames = await sseFrames(url, "SendStreamingMessage", {
1040
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
1041
+ });
1042
+ assert.isAtLeast(frames.length, 2, "artifact + terminal status events");
1043
+ const artifacts = frames.filter((f) => f.result?.artifactUpdate);
1044
+ const statuses = frames.filter((f) => f.result?.statusUpdate);
1045
+ assert.equal(artifacts.length, 1, "one artifact event");
1046
+ assert.equal(statuses.length, 1, "one terminal status event");
1047
+ // TaskArtifactUpdateEvent: {taskId, contextId, artifact, lastChunk}.
1048
+ const ae = artifacts[0]!.result.artifactUpdate;
1049
+ assert.equal(ae.taskId, statuses[0]!.result.statusUpdate.taskId);
1050
+ assert.equal(ae.contextId, statuses[0]!.result.statusUpdate.contextId);
1051
+ assert.match(ae.taskId, /^task-/);
1052
+ assert.match(ae.contextId, /^ctx-/);
1053
+ assert.equal(ae.artifact?.parts?.[0]?.text, "stream body");
1054
+ assert.equal(ae.lastChunk, true);
1055
+ // TaskStatusUpdateEvent: {taskId, contextId, status, final}.
1056
+ const se = statuses[0]!.result.statusUpdate;
1057
+ assert.equal(se.status?.state, STATE_COMPLETED);
1058
+ assert.equal(se.final, true);
1059
+ // The artifact event precedes the terminal status event (the final
1060
+ // frame carries the terminal state).
1061
+ assert.isBelow(frames.indexOf(artifacts[0]!), frames.indexOf(statuses[0]!));
1062
+ // No event may wrap a whole Task (the pre-1.0 shape).
1063
+ for (const f of frames) {
1064
+ assert.notExists(f.result?.task, "stream events must not be whole Tasks");
1065
+ assert.notExists(f.result?.statusUpdate?.artifacts, "statusUpdate must be an event, not a Task");
1066
+ }
1067
+ } finally {
1068
+ await stop();
1069
+ }
1070
+ });
1071
+
1072
+ it("ListTasks returns full Task objects; tasks/list keeps {id,state} stubs", async () => {
1073
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("listed") });
1074
+ try {
1075
+ const send = await jsonRpc(url, "SendMessage", {
1076
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
1077
+ });
1078
+ const tid = sendTask(send).id;
1079
+ const v1 = await jsonRpc(url, "ListTasks", {});
1080
+ assert.isAtLeast(v1.result?.tasks?.length, 1);
1081
+ const mine = v1.result.tasks.find((t: any) => t.id === tid);
1082
+ assert.exists(mine, "the created task is listed");
1083
+ assert.equal(mine.status.state, STATE_COMPLETED);
1084
+ assert.exists(mine.contextId, "full Task object, not an {id,state} stub");
1085
+ const legacy = await jsonRpc(url, "tasks/list", {});
1086
+ const stub = legacy.result.tasks.find((t: any) => t.id === tid);
1087
+ assert.exists(stub);
1088
+ assert.deepEqual(Object.keys(stub).sort(), ["id", "state"], "legacy alias keeps the stub shape");
1089
+ } finally {
1090
+ await stop();
1091
+ }
1092
+ });
1093
+
1094
+ it("SubscribeToTask emits a v1.0 TaskStatusUpdateEvent snapshot", async () => {
1095
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("subscribed") });
1096
+ try {
1097
+ const send = await jsonRpc(url, "SendMessage", {
1098
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
1099
+ });
1100
+ const tid = sendTask(send).id;
1101
+ const frames = await sseFrames(url, "SubscribeToTask", { id: tid }, "sub-v1");
1102
+ assert.isAtLeast(frames.length, 1);
1103
+ const se = frames[0]!.result?.statusUpdate;
1104
+ assert.exists(se, "snapshot statusUpdate event");
1105
+ assert.equal(se.taskId, tid);
1106
+ assert.match(se.contextId, /^ctx-/);
1107
+ assert.equal(se.status?.state, STATE_COMPLETED);
1108
+ assert.equal(se.final, true, "snapshot of a finished task is the final event");
1109
+ assert.notExists(se.artifacts, "statusUpdate must be an event, not a Task");
1110
+ } finally {
1111
+ await stop();
1112
+ }
1113
+ });
1114
+ });
1115
+
1116
+ describe("reply timeout classifies as FAILED (not CANCELED)", () => {
1117
+ it("times out a slow task to STATE_FAILED", async () => {
1118
+ const cfg = DEFAULTS();
1119
+ cfg.server.replyTimeoutSec = 1;
1120
+ const runner: SessionRunner = ({ signal }) =>
1121
+ new Promise((_resolve, reject) => {
1122
+ // Never resolves on its own; waits for abort (timeout), then rejects.
1123
+ signal.addEventListener("abort", () => reject(new Error("timeout")));
1124
+ });
1125
+ const { url, stop } = await startServer({ cfg, runner });
1126
+ try {
1127
+ const r = await jsonRpc(url, "SendMessage", {
1128
+ message: { role: "ROLE_USER", parts: [{ text: "slow" }] },
1129
+ });
1130
+ assert.equal(sendTask(r).status.state, STATE_FAILED);
1131
+ // Classification comes from the abort reason (the supervision ground
1132
+ // truth), not the runner's own "timeout" rejection above.
1133
+ assert.match(sendTask(r).status.message?.parts?.[0]?.text ?? "", /reply timeout/);
1134
+ } finally {
1135
+ await stop();
1136
+ }
1137
+ });
1138
+ });
1139
+
1140
+ describe("non-blocking dispatch (SendMessageConfiguration.returnImmediately)", () => {
1141
+ it("acks WORKING immediately and completes in the background (GetTask)", async () => {
1142
+ const runner: SessionRunner = async () => {
1143
+ await new Promise((res) => setTimeout(res, 300));
1144
+ return { reply: "done eventually", inputRequired: false };
1145
+ };
1146
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner });
1147
+ try {
1148
+ const t0 = Date.now();
1149
+ const r = await jsonRpc(url, "SendMessage", {
1150
+ message: { role: "ROLE_USER", parts: [{ text: "long job" }] },
1151
+ configuration: { returnImmediately: true },
1152
+ });
1153
+ const ackMs = Date.now() - t0;
1154
+ // The ack must NOT wait for the 300ms runner — that is the whole point
1155
+ // of non-blocking dispatch (the caller envelope stops bounding the run).
1156
+ assert.isBelow(ackMs, 200, `ack took ${ackMs}ms; runner should still be pending`);
1157
+ assert.equal(sendTask(r).status.state, STATE_WORKING);
1158
+ assert.match(sendTask(r).id, /^task-/);
1159
+ const task = await pollTask(url, sendTask(r).id);
1160
+ assert.equal(task.status.state, STATE_COMPLETED);
1161
+ assert.equal(task.artifacts?.[0]?.parts?.[0]?.text, "done eventually");
1162
+ } finally {
1163
+ await stop();
1164
+ }
1165
+ });
1166
+
1167
+ it("accepts the snake_case return_immediately spelling", async () => {
1168
+ // Delayed runner: with an instant one the run settles before the HTTP
1169
+ // layer serializes the ack, so the ack legitimately carries the terminal
1170
+ // state (the client handles that — fast tasks just return their result).
1171
+ // A pending runner makes the WORKING assertion meaningful: it only holds
1172
+ // if the server truly returned before the run finished.
1173
+ const runner: SessionRunner = async () => {
1174
+ await new Promise((res) => setTimeout(res, 150));
1175
+ return { reply: "snake ok", inputRequired: false };
1176
+ };
1177
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner });
1178
+ try {
1179
+ const r = await jsonRpc(url, "SendMessage", {
1180
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
1181
+ configuration: { return_immediately: true },
1182
+ });
1183
+ assert.equal(sendTask(r).status.state, STATE_WORKING);
1184
+ const task = await pollTask(url, sendTask(r).id);
1185
+ assert.equal(task.status.state, STATE_COMPLETED);
1186
+ } finally {
1187
+ await stop();
1188
+ }
1189
+ });
1190
+
1191
+ it("a detached run is NOT bounded by the reply window", async () => {
1192
+ // Same config that FAILS a blocking task after 1s (see the reply-timeout
1193
+ // suite above): detached, with the async window disabled (0), the run
1194
+ // must outlive the reply window and complete.
1195
+ const cfg = DEFAULTS();
1196
+ cfg.server.replyTimeoutSec = 1;
1197
+ cfg.server.asyncTimeoutSec = 0;
1198
+ const runner: SessionRunner = async () => {
1199
+ await new Promise((res) => setTimeout(res, 1600));
1200
+ return { reply: "survived the reply window", inputRequired: false };
1201
+ };
1202
+ const { url, stop } = await startServer({ cfg, runner });
1203
+ try {
1204
+ const r = await jsonRpc(url, "SendMessage", {
1205
+ message: { role: "ROLE_USER", parts: [{ text: "outlive the window" }] },
1206
+ configuration: { returnImmediately: true },
1207
+ });
1208
+ assert.equal(sendTask(r).status.state, STATE_WORKING);
1209
+ const task = await pollTask(url, sendTask(r).id, 6000);
1210
+ assert.equal(task.status.state, STATE_COMPLETED);
1211
+ assert.equal(task.artifacts?.[0]?.parts?.[0]?.text, "survived the reply window");
1212
+ } finally {
1213
+ await stop();
1214
+ }
1215
+ });
1216
+
1217
+ it("server.asyncTimeoutSec bounds a detached run and classifies it FAILED", async () => {
1218
+ const cfg = DEFAULTS();
1219
+ cfg.server.asyncTimeoutSec = 1;
1220
+ // The runner rejects with its OWN error on abort (like a session runner
1221
+ // whose prompt rejects with an SDK error) — the server must still
1222
+ // classify by the abort REASON, which carries the descriptive window
1223
+ // message. If it used the runner's error, a dispatcher could not tell a
1224
+ // supervision kill from a worker crash.
1225
+ const runner: SessionRunner = ({ signal }) =>
1226
+ new Promise((_resolve, reject) => {
1227
+ signal.addEventListener("abort", () => reject(new Error("async window hit")));
1228
+ });
1229
+ const { url, stop } = await startServer({ cfg, runner });
1230
+ try {
1231
+ const r = await jsonRpc(url, "SendMessage", {
1232
+ message: { role: "ROLE_USER", parts: [{ text: "hang" }] },
1233
+ configuration: { returnImmediately: true },
1234
+ });
1235
+ assert.equal(sendTask(r).status.state, STATE_WORKING);
1236
+ const task = await pollTask(url, sendTask(r).id, 4000);
1237
+ assert.equal(task.status.state, STATE_FAILED);
1238
+ assert.match(task.status.message?.parts?.[0]?.text ?? "", /async timeout.*detached-task window/);
1239
+ } finally {
1240
+ await stop();
1241
+ }
1242
+ });
1243
+
1244
+ it("tasks/cancel cancels a detached run", async () => {
1245
+ const runner: SessionRunner = ({ signal }) =>
1246
+ new Promise((_resolve, reject) => {
1247
+ signal.addEventListener("abort", () => reject(new Error("canceled")));
1248
+ });
1249
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner });
1250
+ try {
1251
+ const r = await jsonRpc(url, "SendMessage", {
1252
+ message: { role: "ROLE_USER", parts: [{ text: "cancel me" }] },
1253
+ configuration: { returnImmediately: true },
1254
+ });
1255
+ assert.equal(sendTask(r).status.state, STATE_WORKING);
1256
+ const c = await jsonRpc(url, "tasks/cancel", { id: sendTask(r).id });
1257
+ assert.equal(c.result.status.state, STATE_CANCELED);
1258
+ const task = await pollTask(url, sendTask(r).id);
1259
+ assert.equal(task.status.state, STATE_CANCELED);
1260
+ } finally {
1261
+ await stop();
1262
+ }
1263
+ });
1264
+
1265
+ it("a detached runner failure is visible via GetTask as FAILED with the message", async () => {
1266
+ const runner: SessionRunner = async () => {
1267
+ throw new Error("worker exploded");
1268
+ };
1269
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner });
1270
+ try {
1271
+ const r = await jsonRpc(url, "SendMessage", {
1272
+ message: { role: "ROLE_USER", parts: [{ text: "will fail" }] },
1273
+ configuration: { returnImmediately: true },
1274
+ });
1275
+ const task = await pollTask(url, sendTask(r).id);
1276
+ assert.equal(task.status.state, STATE_FAILED);
1277
+ assert.match(task.status.message?.parts?.[0]?.text ?? "", /worker exploded/);
1278
+ } finally {
1279
+ await stop();
1280
+ }
1281
+ });
1282
+
1283
+ it("contains an unexpected throw on the detached path (no unhandled rejection; task FAILED)", async () => {
1284
+ // A failing runner + an onActivity sink that throws on the "failed"
1285
+ // event makes executeTask reject AFTER the ack already returned — the
1286
+ // floating-promise path. The detached observer must contain it: the
1287
+ // task still lands FAILED with the runner's message (set before the
1288
+ // sink threw), and the process must not die of an unhandled rejection.
1289
+ const runner: SessionRunner = async () => {
1290
+ // Fail AFTER the ack is serialized, so the rejection genuinely lands
1291
+ // on the detached path (an instantly-throwing runner can lose the
1292
+ // race and mutate the task before the HTTP layer serializes the ack).
1293
+ await new Promise((res) => setTimeout(res, 150));
1294
+ throw new Error("worker exploded");
1295
+ };
1296
+ const onActivity = (a: any) => {
1297
+ if (a.type === "failed") throw new Error("activity sink exploded");
1298
+ };
1299
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner, onActivity });
1300
+ // Observe process-level unhandled rejections for the duration of the
1301
+ // scenario: the detached `execution` promise must never surface as one.
1302
+ // (A bare test would not discriminate — mocha installs its own
1303
+ // unhandledRejection handler that swallows detached rejections.)
1304
+ let unhandled: unknown = null;
1305
+ const onUnhandled = (e: unknown) => {
1306
+ unhandled = e ?? new Error("unhandled rejection");
1307
+ };
1308
+ process.on("unhandledRejection", onUnhandled);
1309
+ try {
1310
+ const r = await jsonRpc(url, "SendMessage", {
1311
+ message: { role: "ROLE_USER", parts: [{ text: "will fail" }] },
1312
+ configuration: { returnImmediately: true },
1313
+ });
1314
+ assert.equal(sendTask(r).status.state, STATE_WORKING);
1315
+ const task = await pollTask(url, sendTask(r).id);
1316
+ assert.equal(task.status.state, STATE_FAILED);
1317
+ assert.match(task.status.message?.parts?.[0]?.text ?? "", /worker exploded/);
1318
+ // The poll above let the event loop turn; any unhandled rejection
1319
+ // from the detached path has fired by now.
1320
+ assert.isNull(unhandled, `detached path must not produce an unhandled rejection (got: ${String(unhandled)})`);
1321
+ } finally {
1322
+ process.off("unhandledRejection", onUnhandled);
1323
+ await stop();
1324
+ }
1325
+ });
1326
+
1327
+ it("classification is keyed to the supervision timer, not the abort-reason text", async () => {
1328
+ // No supervision timer fires here (replyTimeoutSec is large); the
1329
+ // runner rejects with its own "reply timeout:"-prefixed error. The
1330
+ // task must be FAILED with the runner's message PASSED THROUGH VERBATIM
1331
+ // — supervision wording ("…window") may only ever come from OUR timer,
1332
+ // so a lying runner cannot pose as a supervision kill.
1333
+ const cfg = DEFAULTS();
1334
+ cfg.server.replyTimeoutSec = 60;
1335
+ const runner: SessionRunner = async () => {
1336
+ throw new Error("reply timeout: this text lies");
1337
+ };
1338
+ const { url, stop } = await startServer({ cfg, runner });
1339
+ try {
1340
+ const r = await jsonRpc(url, "SendMessage", {
1341
+ message: { role: "ROLE_USER", parts: [{ text: "spoof attempt" }] },
1342
+ });
1343
+ assert.equal(sendTask(r).status.state, STATE_FAILED);
1344
+ const msg = sendTask(r).status.message?.parts?.[0]?.text ?? "";
1345
+ assert.equal(msg, "reply timeout: this text lies");
1346
+ assert.notInclude(msg, "window");
1347
+ } finally {
1348
+ await stop();
1349
+ }
1350
+ });
1351
+
1352
+ it("replyTimeoutSec 0 means NO reply-window timer (unbounded), not instant timeout", async () => {
1353
+ // Pre-async-dispatch, replyTimeoutSec 0 armed setTimeout(…, 0) = an
1354
+ // instant timeout. The >0 guard redefined 0 to "no timer"; this pins
1355
+ // the documented reading (0 = unbounded, same as asyncTimeoutSec).
1356
+ const cfg = DEFAULTS();
1357
+ cfg.server.replyTimeoutSec = 0;
1358
+ const runner: SessionRunner = async () => {
1359
+ await new Promise((res) => setTimeout(res, 400));
1360
+ return { reply: "outlived a zero window", inputRequired: false };
1361
+ };
1362
+ const { url, stop } = await startServer({ cfg, runner });
1363
+ try {
1364
+ const r = await jsonRpc(url, "SendMessage", {
1365
+ message: { role: "ROLE_USER", parts: [{ text: "slow but allowed" }] },
1366
+ });
1367
+ assert.equal(sendTask(r).status.state, STATE_COMPLETED);
1368
+ assert.equal(sendTask(r).artifacts?.[0]?.parts?.[0]?.text, "outlived a zero window");
1369
+ } finally {
1370
+ await stop();
1371
+ }
1372
+ });
1373
+
1374
+ it("returnImmediately has no effect on message/stream (spec §3.2.2)", async () => {
1375
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stubRunner("streamed reply") });
1376
+ try {
1377
+ const resp = await fetch(url, {
1378
+ method: "POST",
1379
+ headers: { "Content-Type": "application/json" },
1380
+ body: JSON.stringify({
1381
+ jsonrpc: "2.0",
1382
+ id: "sse-async",
1383
+ method: "message/stream",
1384
+ params: {
1385
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
1386
+ configuration: { returnImmediately: true },
1387
+ },
1388
+ }),
1389
+ });
1390
+ const text = await resp.text();
1391
+ const frames = text
1392
+ .split("\n")
1393
+ .filter((l) => l.startsWith("data:"))
1394
+ .map((l) => JSON.parse(l.replace(/^data:\s*/, "")));
1395
+ const statusFrame = frames.find((f) => f.result?.statusUpdate);
1396
+ // Streaming keeps its blocking semantics: the final statusUpdate is the
1397
+ // COMPLETED task, not an early WORKING ack.
1398
+ assert.equal(statusFrame?.result?.statusUpdate?.status?.state, STATE_COMPLETED);
1399
+ } finally {
1400
+ await stop();
1401
+ }
1402
+ });
1403
+ });
1404
+
1405
+ describe("stunted length-stop reply is not COMPLETED", () => {
1406
+ // A context-clamped turn ends with stopReason "length" and no assistant
1407
+ // text (max_tokens squeezed to the remaining context, the model emits
1408
+ // almost nothing). The session runner now throws for such a turn — the
1409
+ // alternative is returning the PREVIOUS turn's text normally, which
1410
+ // takes messageSend's success path: the task completes with a stale
1411
+ // mid-work reply and a dispatcher cannot tell a dead worker from a
1412
+ // finished one. These tests lock the classification the contract
1413
+ // depends on: the throw maps to FAILED with a status message and no
1414
+ // reply artifact.
1415
+ const stuntedRunner: SessionRunner = async () => {
1416
+ throw new Error(
1417
+ "run ended on a length stop with no assistant text — no usable reply was produced (output capped before any content; context-clamped max_tokens?)",
1418
+ );
1419
+ };
1420
+
1421
+ it("maps a length-stop-no-text turn to STATE_FAILED with a status message", async () => {
1422
+ const events: any[] = [];
1423
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stuntedRunner, onActivity: (a) => events.push(a) });
1424
+ try {
1425
+ const r = await jsonRpc(url, "SendMessage", {
1426
+ message: { role: "ROLE_USER", parts: [{ text: "long task" }] },
1427
+ });
1428
+ assert.equal(sendTask(r).status.state, STATE_FAILED);
1429
+ const msgText = sendTask(r).status.message?.parts?.[0]?.text ?? "";
1430
+ assert.include(msgText, "no usable reply", "status message explains the stunted turn");
1431
+ assert.isUndefined(sendTask(r).artifacts, "a stunted turn carries no reply artifact");
1432
+ // The host toast must say failed — not "completed (Ns)".
1433
+ assert.deepEqual(events.map((e) => e.type), ["arrived", "failed"]);
1434
+ } finally {
1435
+ await stop();
1436
+ }
1437
+ });
1438
+
1439
+ it("does not count the stunted turn as completed in metrics", async () => {
1440
+ const before = metrics.tasksCompleted;
1441
+ const beforeFailed = metrics.tasksFailed;
1442
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: stuntedRunner });
1443
+ try {
1444
+ const r = await jsonRpc(url, "SendMessage", {
1445
+ message: { role: "ROLE_USER", parts: [{ text: "long task" }] },
1446
+ });
1447
+ assert.equal(sendTask(r).status.state, STATE_FAILED);
1448
+ assert.equal(metrics.tasksCompleted, before, "stunted turns never increment completions");
1449
+ assert.equal(metrics.tasksFailed, beforeFailed + 1, "stunted turns increment failures");
1450
+ } finally {
1451
+ await stop();
1452
+ }
1453
+ });
1454
+ });
1455
+
1456
+ describe("reply-window timer teardown (#257)", () => {
1457
+ it("clears the reply-window watchdog when the runner throws — no leaked 300s timer", async () => {
1458
+ // Regression (#257): a throwing runner skips the success-path
1459
+ // clearTimeout and never aborts the controller, so the 5-minute
1460
+ // reply-window timer stayed armed after the task reported FAILED —
1461
+ // the task was dead but the timer kept the process's event loop alive
1462
+ // for the full window (the test-suite exit-hang). Every exit path must
1463
+ // clear it.
1464
+ const cfg = DEFAULTS(); // replyTimeoutSec: 300 → watchdog delay 300000ms
1465
+ const windowMs = cfg.server.replyTimeoutSec * 1000;
1466
+ const runner: SessionRunner = async () => {
1467
+ throw new Error("boom");
1468
+ };
1469
+ const { url, stop } = await startServer({ cfg, runner });
1470
+ const origSetTimeout = globalThis.setTimeout;
1471
+ const origClearTimeout = globalThis.clearTimeout;
1472
+ let created = 0;
1473
+ const armed = new Set<ReturnType<typeof setTimeout>>();
1474
+ try {
1475
+ (globalThis as any).setTimeout = (fn: any, delay?: number, ...args: any[]) => {
1476
+ const t = origSetTimeout(fn, delay, ...args);
1477
+ if (delay === windowMs) {
1478
+ created += 1;
1479
+ armed.add(t);
1480
+ }
1481
+ return t;
1482
+ };
1483
+ (globalThis as any).clearTimeout = (t: ReturnType<typeof setTimeout>) => {
1484
+ armed.delete(t);
1485
+ return origClearTimeout(t);
1486
+ };
1487
+ const r = await jsonRpc(url, "SendMessage", {
1488
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
1489
+ });
1490
+ assert.equal(sendTask(r).status.state, STATE_FAILED);
1491
+ } finally {
1492
+ (globalThis as any).setTimeout = origSetTimeout;
1493
+ (globalThis as any).clearTimeout = origClearTimeout;
1494
+ await stop();
1495
+ }
1496
+ assert.equal(created, 1, "the reply-window watchdog must be created for the task");
1497
+ assert.equal(armed.size, 0, "reply-window timer must be cleared when the runner throws");
1498
+ });
1499
+ });
1500
+
1501
+ describe("aborted runner returning normally is not COMPLETED (#247)", () => {
1502
+ // The stock session runner resolves its prompt promise on session.abort()
1503
+ // (instead of rejecting) and used to return the truncated reply normally,
1504
+ // which took messageSend's success path: a reply-window kill came back
1505
+ // TASK_STATE_COMPLETED with a partial artifact — indistinguishable from
1506
+ // a finished worker. The server must classify by the abort signal, not
1507
+ // by how the runner happened to return.
1508
+ const partialRunner: SessionRunner = ({ signal }) =>
1509
+ new Promise((resolve) => {
1510
+ // Mimics the stock runner: abort resolves it normally with whatever
1511
+ // partial reply was captured so far.
1512
+ signal.addEventListener(
1513
+ "abort",
1514
+ () => resolve({ reply: "partial work before the window closed", inputRequired: false }),
1515
+ { once: true },
1516
+ );
1517
+ });
1518
+
1519
+ it("maps a reply-window timeout to STATE_FAILED with a timeout status message", async () => {
1520
+ const cfg = DEFAULTS();
1521
+ cfg.server.replyTimeoutSec = 1;
1522
+ const events: any[] = [];
1523
+ const { url, stop } = await startServer({ cfg, runner: partialRunner, onActivity: (a) => events.push(a) });
1524
+ try {
1525
+ const r = await jsonRpc(url, "SendMessage", {
1526
+ message: { role: "ROLE_USER", parts: [{ text: "long task" }] },
1527
+ });
1528
+ assert.equal(sendTask(r).status.state, STATE_FAILED);
1529
+ const msgText = sendTask(r).status.message?.parts?.[0]?.text ?? "";
1530
+ assert.include(msgText, "reply timeout", "status message names the timeout");
1531
+ assert.isUndefined(sendTask(r).artifacts, "an aborted task carries no reply artifact");
1532
+ // The host toast must say failed — not "completed (Ns)".
1533
+ assert.deepEqual(events.map((e) => e.type), ["arrived", "failed"]);
1534
+ } finally {
1535
+ await stop();
1536
+ }
1537
+ });
1538
+
1539
+ it("preserves STATE_CANCELED when a canceled runner returns normally", async () => {
1540
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner: partialRunner });
1541
+ try {
1542
+ const sendP = jsonRpc(url, "SendMessage", {
1543
+ message: { role: "ROLE_USER", parts: [{ text: "long task" }] },
1544
+ });
1545
+ // Let the task start, then cancel it.
1546
+ await new Promise((r) => setTimeout(r, 50));
1547
+ const tasks = await jsonRpc(url, "tasks/list", {});
1548
+ const tid = tasks.result.tasks[0]!.id;
1549
+ await jsonRpc(url, "tasks/cancel", { id: tid });
1550
+ const send = await sendP;
1551
+ // The success path used to clobber the cancel handler's CANCELED.
1552
+ assert.equal(sendTask(send).status.state, STATE_CANCELED);
1553
+ } finally {
1554
+ await stop();
1555
+ }
1556
+ });
1557
+ });
1558
+
1559
+ describe("child transcripts (#252)", () => {
1560
+ it("passes the A2A taskId to the runner", async () => {
1561
+ let seenTaskId: string | undefined;
1562
+ const runner: SessionRunner = async ({ taskId }) => {
1563
+ seenTaskId = taskId;
1564
+ return { reply: "ok", inputRequired: false };
1565
+ };
1566
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner });
1567
+ try {
1568
+ const r = await jsonRpc(url, "SendMessage", {
1569
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
1570
+ });
1571
+ assert.equal(sendTask(r).status.state, STATE_COMPLETED);
1572
+ assert.equal(seenTaskId, sendTask(r).id, "runner receives the task's own A2A id");
1573
+ assert.match(seenTaskId ?? "", /^task-/);
1574
+ } finally {
1575
+ await stop();
1576
+ }
1577
+ });
1578
+
1579
+ it("audits the transcript path + step count on completion", async () => {
1580
+ const piDir = tmpDir();
1581
+ const runner: SessionRunner = async () => ({
1582
+ reply: "done",
1583
+ inputRequired: false,
1584
+ transcriptPath: "/tmp/a2a_sessions/20260830T000000_task-abc.jsonl",
1585
+ stepCount: 7,
1586
+ });
1587
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner, piDir });
1588
+ try {
1589
+ const r = await jsonRpc(url, "SendMessage", {
1590
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
1591
+ });
1592
+ assert.equal(sendTask(r).status.state, STATE_COMPLETED);
1593
+ const lines = fs
1594
+ .readFileSync(path.join(piDir, "a2a_audit.jsonl"), "utf-8")
1595
+ .split("\n")
1596
+ .filter(Boolean)
1597
+ .map((l) => JSON.parse(l));
1598
+ const tp = lines.find((l) => l.transcript);
1599
+ assert.ok(tp, "a transcript audit line exists");
1600
+ assert.equal(tp.taskId, sendTask(r).id);
1601
+ assert.equal(tp.transcript, "/tmp/a2a_sessions/20260830T000000_task-abc.jsonl");
1602
+ assert.match(tp.preview, /7 steps/);
1603
+ } finally {
1604
+ await stop();
1605
+ }
1606
+ });
1607
+
1608
+ it("audits the transcript path when the runner throws (killed worker)", async () => {
1609
+ const piDir = tmpDir();
1610
+ const runner: SessionRunner = async () => {
1611
+ const err = new Error("reply timeout: exceeded the 1800s reply window");
1612
+ (err as any).transcriptPath = "/tmp/a2a_sessions/20260830T000000_task-def.jsonl";
1613
+ (err as any).stepCount = 42;
1614
+ throw err;
1615
+ };
1616
+ const { url, stop } = await startServer({ cfg: DEFAULTS(), runner, piDir });
1617
+ try {
1618
+ const r = await jsonRpc(url, "SendMessage", {
1619
+ message: { role: "ROLE_USER", parts: [{ text: "hi" }] },
1620
+ });
1621
+ assert.equal(sendTask(r).status.state, STATE_FAILED);
1622
+ const lines = fs
1623
+ .readFileSync(path.join(piDir, "a2a_audit.jsonl"), "utf-8")
1624
+ .split("\n")
1625
+ .filter(Boolean)
1626
+ .map((l) => JSON.parse(l));
1627
+ const tp = lines.find((l) => l.transcript);
1628
+ assert.ok(tp, "a transcript audit line exists for the failure");
1629
+ assert.match(tp.preview, /42 steps/);
1630
+ } finally {
1631
+ await stop();
1632
+ }
1633
+ });
1634
+
1635
+ it("carries the transcript on the error when an aborted runner returns normally", async () => {
1636
+ // The #247 defense-in-depth path: the runner resolves normally on
1637
+ // abort, and messageSend must reclassify as FAILED — carrying the
1638
+ // transcript forensics onto the classification error.
1639
+ const piDir = tmpDir();
1640
+ const partialRunner: SessionRunner = ({ signal }) =>
1641
+ new Promise((resolve) => {
1642
+ signal.addEventListener(
1643
+ "abort",
1644
+ () =>
1645
+ resolve({
1646
+ reply: "partial",
1647
+ inputRequired: false,
1648
+ transcriptPath: "/tmp/a2a_sessions/20260830T000000_task-ghi.jsonl",
1649
+ stepCount: 3,
1650
+ }),
1651
+ { once: true },
1652
+ );
1653
+ });
1654
+ const cfg = DEFAULTS();
1655
+ cfg.server.replyTimeoutSec = 1;
1656
+ const { url, stop } = await startServer({ cfg, runner: partialRunner, piDir });
1657
+ try {
1658
+ const r = await jsonRpc(url, "SendMessage", {
1659
+ message: { role: "ROLE_USER", parts: [{ text: "long task" }] },
1660
+ });
1661
+ assert.equal(sendTask(r).status.state, STATE_FAILED);
1662
+ const lines = fs
1663
+ .readFileSync(path.join(piDir, "a2a_audit.jsonl"), "utf-8")
1664
+ .split("\n")
1665
+ .filter(Boolean)
1666
+ .map((l) => JSON.parse(l));
1667
+ const tp = lines.find((l) => l.transcript);
1668
+ assert.ok(tp, "transcript audited despite the post-abort normal return");
1669
+ assert.match(tp.preview, /3 steps/);
1670
+ } finally {
1671
+ await stop();
1672
+ }
1673
+ });
1674
+ });
1675
+
1676
+ describe("port fallback (EADDRINUSE → next port)", () => {
1677
+ /** Pre-bind the configured port so the A2A server must fall back. */
1678
+ async function holdPort(port: number): Promise<() => Promise<void>> {
1679
+ const srv = createServer();
1680
+ await new Promise<void>((resolve, reject) => {
1681
+ srv.once("error", reject);
1682
+ srv.listen(port, "127.0.0.1", () => resolve());
1683
+ });
1684
+ return () => new Promise<void>((resolve) => srv.close(() => resolve()));
1685
+ }
1686
+
1687
+ it("binds port+1 when the configured port is busy, and advertises it", async () => {
1688
+ const port = await freePort();
1689
+ const release = await holdPort(port); // 9910-equivalent now busy
1690
+ const cfg = DEFAULTS();
1691
+ cfg.server.port = port;
1692
+ cfg.server.portFallback = 5;
1693
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1694
+ try {
1695
+ const info = await server.start();
1696
+ assert.equal(info.port, port + 1, "should have climbed to port+1");
1697
+ assert.equal(server.port, port + 1, "boundPort getter reflects actual");
1698
+ // The Agent Card must advertise the ACTUAL port, not the busy configured one.
1699
+ const cardResp = await fetch(info.url + ".well-known/agent-card.json");
1700
+ const card = await cardResp.json();
1701
+ assert.include(card.supportedInterfaces[0].url, `:${port + 1}`, "card advertises the fallback port");
1702
+ } finally {
1703
+ await server.stop();
1704
+ await release();
1705
+ }
1706
+ });
1707
+
1708
+ it("falls back to OS-assigned port when all explicit ports are busy", async () => {
1709
+ const port = await freePort();
1710
+ const release = await holdPort(port);
1711
+ const cfg = DEFAULTS();
1712
+ cfg.server.port = port;
1713
+ cfg.server.portFallback = 0; // configured port only, then OS-assigned
1714
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1715
+ try {
1716
+ const info = await server.start();
1717
+ assert.notEqual(info.port, port, "must NOT use the busy configured port");
1718
+ assert.isAbove(info.port, 0);
1719
+ // Card reflects the OS-assigned port.
1720
+ const cardResp = await fetch(info.url + ".well-known/agent-card.json");
1721
+ const card = await cardResp.json();
1722
+ assert.include(card.supportedInterfaces[0].url, `:${info.port}`);
1723
+ } finally {
1724
+ await server.stop();
1725
+ await release();
1726
+ }
1727
+ });
1728
+
1729
+ it("binds the configured port when free (no fallback)", async () => {
1730
+ const port = await freePort();
1731
+ const cfg = DEFAULTS();
1732
+ cfg.server.port = port;
1733
+ cfg.server.portFallback = 10;
1734
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1735
+ try {
1736
+ const info = await server.start();
1737
+ assert.equal(info.port, port, "happy path binds configured port exactly");
1738
+ } finally {
1739
+ await server.stop();
1740
+ }
1741
+ });
1742
+
1743
+ it("explicit port 0 starts on an OS-assigned ephemeral port", async () => {
1744
+ const cfg = DEFAULTS();
1745
+ cfg.server.port = 0; // user explicitly wants ephemeral
1746
+ cfg.server.portFallback = 10;
1747
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1748
+ try {
1749
+ const info = await server.start();
1750
+ assert.isAbove(info.port, 0, "must get a real ephemeral port");
1751
+ assert.notEqual(info.port, 0);
1752
+ assert.equal(server.port, info.port, "boundPort getter reflects the ephemeral port");
1753
+ const cardResp = await fetch(info.url + ".well-known/agent-card.json");
1754
+ const card = await cardResp.json();
1755
+ assert.include(card.supportedInterfaces[0].url, `:${info.port}`, "card advertises the ephemeral port");
1756
+ } finally {
1757
+ await server.stop();
1758
+ }
1759
+ });
1760
+
1761
+ it("url getter returns empty after stop (no stale port)", async () => {
1762
+ const cfg = DEFAULTS();
1763
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1764
+ await server.start();
1765
+ assert.notEqual(server.url, "");
1766
+ assert.isNotNull(server.port);
1767
+ await server.stop();
1768
+ assert.equal(server.url, "", "stopped server must not advertise a port");
1769
+ assert.isNull(server.port, "stopped server port is null");
1770
+ });
1771
+ });
1772
+
1773
+ describe("gateway registration gating (0.5.0)", () => {
1774
+ let realFetch: typeof fetch;
1775
+ let calls: Array<{ url: string; init?: RequestInit }>;
1776
+
1777
+ beforeEach(() => {
1778
+ realFetch = globalThis.fetch;
1779
+ calls = [];
1780
+ // Stub fetch: record every request; the gateway is never reachable.
1781
+ // Any /register or /channel attempt therefore fails (network error →
1782
+ // register() returns false silently), but we can OBSERVE the attempt.
1783
+ (globalThis as any).fetch = async (url: any, init?: RequestInit) => {
1784
+ calls.push({ url: String(url), init });
1785
+ throw new Error("gateway unreachable (stubbed)");
1786
+ };
1787
+ });
1788
+
1789
+ afterEach(() => {
1790
+ (globalThis as any).fetch = realFetch;
1791
+ setGatewayRegistrationName(null);
1792
+ });
1793
+
1794
+ it("does not register when gateway.enabled is false (no fetch attempt)", async () => {
1795
+ const cfg = DEFAULTS();
1796
+ cfg.discovery.gateway = { enabled: false, url: "http://127.0.0.1:9920", token: "x" };
1797
+ const port = await freePort();
1798
+ cfg.server = { ...cfg.server, port };
1799
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1800
+ await server.start();
1801
+ await server.stop();
1802
+ // The gate must short-circuit BEFORE any network call: no register,
1803
+ // no channel, no directory fetch.
1804
+ assert.equal(calls.length, 0, "disabled gateway must make zero fetch calls");
1805
+ });
1806
+
1807
+ it("attempts registration when gateway.enabled is true", async () => {
1808
+ const cfg = DEFAULTS();
1809
+ cfg.discovery.gateway = { enabled: true, url: "http://127.0.0.1:9920", token: "x" };
1810
+ const port = await freePort();
1811
+ cfg.server = { ...cfg.server, port };
1812
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1813
+ await server.start();
1814
+ // The resolved registration name is NOT published when the gateway is
1815
+ // unreachable — a caller name must not be advertised before a
1816
+ // successful register (X-Gateway-Caller producer side).
1817
+ const key = gatewayKeyFromUrl("http://127.0.0.1:9920");
1818
+ assert.isNull(getGatewayCallerName(key), "no registration name while registration failed");
1819
+ await server.stop();
1820
+ // Registration is attempted (POST /register) even though the gateway is
1821
+ // unreachable. The reverse channel only opens AFTER a successful
1822
+ // register, so with a failing stub there is no /channel call yet — the
1823
+ // enabled:false test above proves the gate itself is what suppresses
1824
+ // every call.
1825
+ const urls = calls.map((c) => c.url);
1826
+ assert.ok(urls.some((u) => u.includes("/register")), "register attempted: " + urls.join(", "));
1827
+ });
1828
+
1829
+ it("an unreachable gateway never blocks server.start() (fire-and-forget, 0.7.13)", async () => {
1830
+ // A never-settling fetch simulates a black-holed switchboard. Pre-0.7.12
1831
+ // start() awaited the register (10s network timeout) and stalled session
1832
+ // start; it must now return immediately and let the heartbeat self-heal.
1833
+ const cfg = DEFAULTS();
1834
+ cfg.discovery.gateway = { enabled: true, url: "http://127.0.0.1:9920", token: "x" };
1835
+ const port = await freePort();
1836
+ cfg.server = { ...cfg.server, port };
1837
+ const realFetch = globalThis.fetch;
1838
+ (globalThis as any).fetch = () => new Promise(() => { /* black hole */ });
1839
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1840
+ try {
1841
+ const t0 = Date.now();
1842
+ await server.start();
1843
+ const elapsed = Date.now() - t0;
1844
+ assert.isBelow(elapsed, 5000, "register await would burn 10s+ here");
1845
+ } finally {
1846
+ (globalThis as any).fetch = realFetch;
1847
+ await server.stop(); // bounded by the 1.5s dereg timeout, not the black hole
1848
+ }
1849
+ });
1850
+
1851
+ it("registers to EACH enabled gateway in the gateways map (0.6.0)", async () => {
1852
+ const cfg = DEFAULTS();
1853
+ cfg.discovery.gateways = {
1854
+ work: { enabled: true, url: "http://127.0.0.1:9920", token: "x" },
1855
+ lab: { enabled: true, url: "http://127.0.0.1:9921", token: "y" },
1856
+ off: { enabled: false, url: "http://127.0.0.1:9922", token: "z" },
1857
+ };
1858
+ const port = await freePort();
1859
+ cfg.server = { ...cfg.server, port };
1860
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1861
+ await server.start();
1862
+ await server.stop();
1863
+ const urls = calls.map((c) => c.url);
1864
+ // 2 enabled gateways → 2 POST /register attempts (the DELETE-on-stop
1865
+ // calls carry ?name= and must not count); disabled one skipped.
1866
+ const posts = urls.filter((u) => u.includes("/register") && !u.includes("?name="));
1867
+ assert.equal(posts.length, 2, urls.join(", "));
1868
+ assert.ok(posts.some((u) => u.includes("9920")), "work gateway registered");
1869
+ assert.ok(posts.some((u) => u.includes("9921")), "lab gateway registered");
1870
+ assert.ok(!urls.some((u) => u.includes("9922")), "disabled gateway must not be touched");
1871
+ });
1872
+
1873
+ it("mints a per-session upstream_token and accepts it inbound (no explicit upstreamToken)", async () => {
1874
+ const cfg = DEFAULTS();
1875
+ cfg.discovery.gateway = { enabled: true, url: "http://127.0.0.1:9920", token: "x" };
1876
+ const port = await freePort();
1877
+ cfg.server = { ...cfg.server, port };
1878
+ const piDir = tmpDir();
1879
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir, runner: stubRunner("ok") });
1880
+ await server.start();
1881
+ // Register body must carry a minted agw-* upstream_token.
1882
+ const post = calls.find((c) => (c.init as any)?.method === "POST");
1883
+ const body = JSON.parse(String(post?.init?.body ?? "{}"));
1884
+ assert.match(String(body.upstream_token), /^agw-/);
1885
+ // The minted token authenticates inbound (extraTokens path) WITHOUT
1886
+ // flipping cfg.server.peerTokens (localhostOnly must stay untouched).
1887
+ const minted = (server as any).mintedInboundTokens[String(body.name)] as string;
1888
+ assert.equal(minted, body.upstream_token);
1889
+ assert.equal(Object.keys(cfg.server.peerTokens).length, 0, "peerTokens config untouched");
1890
+ assert.equal(
1891
+ authenticate({ authHeader: `Bearer ${minted}`, clientIp: "127.0.0.1", peerTokens: {}, sharedToken: "", extraTokens: (server as any).mintedInboundTokens }),
1892
+ String(body.name),
1893
+ );
1894
+ // No-token loopback deployment stays anonymous-friendly: absent bearer
1895
+ // still authenticates as ip: (minted map alone must not require a token).
1896
+ assert.match(
1897
+ String(authenticate({ authHeader: null, clientIp: "127.0.0.1", peerTokens: {}, sharedToken: "", extraTokens: (server as any).mintedInboundTokens })),
1898
+ /^ip:/,
1899
+ );
1900
+ await server.stop();
1901
+ });
1902
+
1903
+ it("two unnamed gateway entries mint DISTINCT tokens, both authenticate inbound", async () => {
1904
+ const cfg = DEFAULTS();
1905
+ cfg.discovery.gateways = {
1906
+ work: { enabled: true, url: "http://127.0.0.1:9920", token: "x" },
1907
+ lab: { enabled: true, url: "http://127.0.0.1:9921", token: "y" },
1908
+ };
1909
+ const port = await freePort();
1910
+ cfg.server = { ...cfg.server, port };
1911
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1912
+ await server.start();
1913
+ // Both entries share the auto-name base-port — tokens must still differ.
1914
+ const posts = calls.filter((c) => (c.init as any)?.method === "POST" && String(c.url).includes("/register"));
1915
+ const tokens = posts.map((c) => JSON.parse(String(c.init?.body ?? "{}")).upstream_token as string);
1916
+ assert.equal(tokens.length, 2);
1917
+ assert.notEqual(tokens[0], tokens[1], "per-gateway tokens must not collide");
1918
+ const minted = (server as any).mintedInboundTokens as Record<string, string>;
1919
+ // Same peer name → last mint wins the name→token identity, but BOTH
1920
+ // tokens authenticate (identity = the name either way).
1921
+ for (const t of tokens) {
1922
+ assert.isString(
1923
+ authenticate({ authHeader: `Bearer ${t}`, clientIp: "10.0.0.9", peerTokens: {}, sharedToken: "", extraTokens: minted }),
1924
+ `token ${t} must authenticate`,
1925
+ );
1926
+ }
1927
+ await server.stop();
1928
+ });
1929
+
1930
+ it("two gateways pinned to the SAME name mint distinct keys — both authenticate", async () => {
1931
+ const cfg = DEFAULTS();
1932
+ cfg.discovery.gateways = {
1933
+ work: { enabled: true, url: "http://127.0.0.1:9920", token: "x", name: "pi" },
1934
+ lab: { enabled: true, url: "http://127.0.0.1:9921", token: "y", name: "pi" },
1935
+ };
1936
+ const port = await freePort();
1937
+ cfg.server = { ...cfg.server, port };
1938
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1939
+ await server.start();
1940
+ const minted = (server as any).mintedInboundTokens as Record<string, string>;
1941
+ const keys = Object.keys(minted);
1942
+ assert.equal(keys.length, 2, "both minting entries retain their token");
1943
+ assert.notEqual(minted[keys[0]!], minted[keys[1]!]);
1944
+ for (const k of keys) {
1945
+ assert.isString(
1946
+ authenticate({ authHeader: `Bearer ${minted[k]}`, clientIp: "10.0.0.9", peerTokens: {}, sharedToken: "", extraTokens: minted }),
1947
+ `token for ${k} must authenticate`,
1948
+ );
1949
+ }
1950
+ await server.stop();
1951
+ });
1952
+
1953
+ it("keeps an explicitly-pinned upstreamToken untouched", async () => {
1954
+ const cfg = DEFAULTS();
1955
+ cfg.discovery.gateway = { enabled: true, url: "http://127.0.0.1:9920", token: "x", upstreamToken: "pinned-tok" };
1956
+ const port = await freePort();
1957
+ cfg.server = { ...cfg.server, port };
1958
+ const server = new A2AServer({ cfg, cwd: tmpDir(), piDir: tmpDir(), runner: stubRunner("ok") });
1959
+ await server.start();
1960
+ const post2 = calls.find((c) => (c.init as any)?.method === "POST");
1961
+ const body = JSON.parse(String(post2?.init?.body ?? "{}"));
1962
+ assert.equal(body.upstream_token, "pinned-tok");
1963
+ await server.stop();
1964
+ });
1965
+ });
1966
+ });