@arnilo/prism-hosts 0.13.1 → 0.14.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 (127) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/a2a/README.md +195 -0
  3. package/a2a/src/card.ts +208 -0
  4. package/a2a/src/codec.ts +523 -0
  5. package/a2a/src/connect.ts +415 -0
  6. package/a2a/src/errors.ts +87 -0
  7. package/a2a/src/index.ts +40 -0
  8. package/a2a/src/limits.ts +43 -0
  9. package/a2a/src/pending.ts +28 -0
  10. package/a2a/src/proxy.ts +526 -0
  11. package/a2a/src/serve.ts +886 -0
  12. package/acp/README.md +3 -1
  13. package/acp/src/limits.ts +3 -16
  14. package/acp/src/mapper.ts +26 -5
  15. package/acp/src/serve.ts +6 -5
  16. package/ag-ui/README.md +2 -1
  17. package/ag-ui/src/a2ui.ts +8 -31
  18. package/ag-ui/src/ag-ui-mapper.ts +27 -1
  19. package/ag-ui/src/encrypted-value.ts +3 -3
  20. package/ag-ui/src/handler.ts +4 -4
  21. package/ag-ui/src/index.ts +0 -33
  22. package/ag-ui/src/limits.ts +5 -88
  23. package/ag-ui/src/projectors.ts +8 -6
  24. package/ag-ui/src/renderer/bind.ts +2 -1
  25. package/channels/README.md +61 -5
  26. package/channels/src/discord-gateway.ts +354 -0
  27. package/channels/src/discord.ts +873 -0
  28. package/channels/src/index.ts +4 -2
  29. package/channels/src/limits.ts +3 -19
  30. package/channels/src/pairing.ts +1 -2
  31. package/channels/src/runtime-turn.ts +10 -2
  32. package/channels/src/signal.ts +11 -19
  33. package/channels/src/slack.ts +854 -0
  34. package/channels/src/telegram.ts +22 -44
  35. package/channels/src/types.ts +5 -2
  36. package/devtools/README.md +1 -1
  37. package/driver-process/src/driver.ts +3 -1
  38. package/driver-process/src/testing.ts +1 -1
  39. package/driver-process/src/turn.ts +5 -1
  40. package/evals/README.md +11 -7
  41. package/evals/src/calibration.ts +5 -13
  42. package/evals/src/compare-experiments.ts +1 -2
  43. package/evals/src/comparison.ts +7 -25
  44. package/evals/src/curate.ts +3 -9
  45. package/evals/src/dataset.ts +0 -2
  46. package/evals/src/index.ts +3 -20
  47. package/evals/src/injection.ts +33 -6
  48. package/evals/src/judge.ts +9 -13
  49. package/evals/src/limits.ts +0 -17
  50. package/evals/src/rubric-judge.ts +5 -10
  51. package/evals/src/scenario-runner.ts +8 -4
  52. package/evals/src/scenarios.ts +5 -5
  53. package/evals/src/score.ts +3 -5
  54. package/evals/src/stats.ts +0 -2
  55. package/evals/src/threshold.ts +3 -3
  56. package/evals/src/toolless-session.ts +7 -3
  57. package/evals/src/trace.ts +8 -14
  58. package/evals/src/trajectory.ts +45 -11
  59. package/evals/src/types.ts +2 -2
  60. package/evals/src/user-simulator.ts +1 -7
  61. package/evals/src/util.ts +3 -9
  62. package/headless/README.md +20 -1
  63. package/headless/src/authority.ts +14 -1
  64. package/headless/src/errors.ts +3 -1
  65. package/headless/src/index.ts +10 -1
  66. package/headless/src/limits.ts +2 -2
  67. package/headless/src/pending.ts +4 -3
  68. package/headless/src/recover.ts +126 -0
  69. package/headless/src/resume.ts +1 -1
  70. package/host-builder/data/api.json +1271 -1360
  71. package/host-builder/data/errors.json +199 -185
  72. package/host-builder/data/examples/a2a-client.ts +125 -0
  73. package/host-builder/data/examples/a2a-server.ts +133 -0
  74. package/host-builder/data/examples/autonomous-coding-loop.ts +1 -1
  75. package/host-builder/data/examples/build-workflow.ts +2 -2
  76. package/host-builder/data/examples/caveman-ponytail.ts +1 -1
  77. package/host-builder/data/examples/channel-discord.ts +176 -0
  78. package/host-builder/data/examples/channel-slack.ts +146 -0
  79. package/host-builder/data/examples/continue-after-failure.ts +80 -0
  80. package/host-builder/data/examples/custom-adapter.ts +1 -1
  81. package/host-builder/data/examples/decision-models.ts +1 -1
  82. package/host-builder/data/examples/define-package.ts +1 -1
  83. package/host-builder/data/examples/delegate.ts +74 -9
  84. package/host-builder/data/examples/durable-loops-and-approvals.ts +11 -10
  85. package/host-builder/data/examples/governance-deny.ts +1 -1
  86. package/host-builder/data/examples/guardrail-content.ts +126 -0
  87. package/host-builder/data/examples/headless-host.ts +1 -1
  88. package/host-builder/data/examples/long-running-job.ts +129 -0
  89. package/host-builder/data/examples/long-term-memory.ts +1 -1
  90. package/host-builder/data/examples/mcp-oauth.ts +197 -0
  91. package/host-builder/data/examples/mcp-trust.ts +1 -1
  92. package/host-builder/data/examples/memory-and-wiki.ts +2 -2
  93. package/host-builder/data/examples/memory-system.ts +19 -9
  94. package/host-builder/data/examples/model-router-aggregate-budgets.ts +1 -1
  95. package/host-builder/data/examples/parallel-tools.ts +70 -0
  96. package/host-builder/data/examples/remote-agent.ts +1 -1
  97. package/host-builder/data/examples/serve-tools.ts +1 -1
  98. package/host-builder/data/examples/session-memory.ts +18 -16
  99. package/host-builder/data/examples/side-call.ts +1 -1
  100. package/host-builder/data/examples/sqlite-resume.ts +1 -1
  101. package/host-builder/data/examples/structured-output.ts +57 -0
  102. package/host-builder/data/examples.json +14 -4
  103. package/host-builder/skills/prism-host-builder/SKILL.md +1 -1
  104. package/host-builder/skills/prism-host-builder/references/choosing.md +14 -10
  105. package/host-builder/skills/prism-host-builder/references/pitfalls.md +5 -3
  106. package/host-builder/skills/prism-host-builder/references/recipes.md +5 -5
  107. package/host-builder/skills/prism-host-builder/references/verification.md +1 -1
  108. package/host-builder/src/check/runner.ts +2 -3
  109. package/host-builder/src/server.ts +2 -2
  110. package/mcp-server/README.md +3 -3
  111. package/mcp-server/src/bounds.ts +3 -3
  112. package/mcp-server/src/serve-tools.ts +2 -9
  113. package/mcp-server/src/serve.ts +2 -4
  114. package/mcp-server/src/server.ts +10 -20
  115. package/package.json +12 -6
  116. package/remote/README.md +7 -4
  117. package/remote/src/channel.ts +6 -2
  118. package/remote/src/connect.ts +9 -3
  119. package/remote/src/errors.ts +3 -1
  120. package/remote/src/limits.ts +3 -13
  121. package/remote/src/mirror.ts +2 -1
  122. package/remote/src/pending.ts +4 -3
  123. package/remote/src/protocol.ts +3 -0
  124. package/remote/src/serve.ts +43 -5
  125. package/remote/src/session-proxy.ts +28 -5
  126. package/remote/src/testing.ts +3 -1
  127. package/remote/src/wire.ts +74 -14
@@ -0,0 +1,415 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ type Agent,
4
+ type AgentEvent,
5
+ type AgentInspection,
6
+ type CredentialResolver,
7
+ createEnvRefCredentialResolver,
8
+ type EventOrigin,
9
+ type HostUi,
10
+ type JsonObject,
11
+ } from "@arnilo/prism";
12
+ import { defaultResolver, isLoopbackHostname, pinnedFetch, resolvePinnedAddress } from "@arnilo/prism/net";
13
+ import { type A2AAgentCard, type PeerCard, readPeerCard } from "./card.js";
14
+ import { A2A_CARD_PATH, A2A_PROTOCOL_VERSION, type A2AStreamResponse, isA2AId, parseA2AStreamResponse } from "./codec.js";
15
+ import { A2AClientError, A2AError, a2aErrorNameOf, A2ALiteralSecretError } from "./errors.js";
16
+ import { type A2ALimitOptions, type ResolvedA2ALimits, resolveA2ALimits } from "./limits.js";
17
+ import { createA2ASession, type A2AContextState, type A2ASessionHandle } from "./proxy.js";
18
+
19
+ /** The peer to connect to. */
20
+ export interface A2AEndpoint {
21
+ /**
22
+ * The peer's Agent Card URL, or any URL on the peer's origin: unless the path ends in `agent-card.json`,
23
+ * the card is read from that origin's `/.well-known/agent-card.json`.
24
+ */
25
+ readonly url: string;
26
+ /** `env:` / `keyring:` ref to a Bearer token, sent only to the card's JSON-RPC endpoint. A literal throws. */
27
+ readonly token?: string;
28
+ /** A card the host already holds (no card fetch). It is validated exactly as a fetched one. */
29
+ readonly card?: A2AAgentCard;
30
+ }
31
+
32
+ export interface ConnectA2AOptions {
33
+ /**
34
+ * Answers the peer's `TASK_STATE_INPUT_REQUIRED` decisions (a `confirm` per approval, an `input` per
35
+ * elicitation) and continues the task in the same run. Without it, or when it answers `unavailable`, the
36
+ * run settles `suspended` with `pending`, and `session.resume(decisions)` sends the answers.
37
+ */
38
+ readonly host?: { readonly ui?: HostUi };
39
+ /** Uses `maxRequestBytes`, `maxResponseBytes`, `maxStreamBytes`, `maxStreamEvents`, `maxStreamMs`, `taskTimeoutMs`, `maxParts`. */
40
+ readonly limits?: A2ALimitOptions;
41
+ /** Allow an `http:` or `https:` loopback peer (local development, tests). Every other private address is refused. */
42
+ readonly allowLoopback?: boolean;
43
+ /** More origins the card's JSON-RPC endpoint may be on. By default it must be the card URL's origin. */
44
+ readonly allowedOrigins?: readonly string[];
45
+ /** Resolves `token`. Defaults to the kernel `env:` resolver. */
46
+ readonly credentials?: CredentialResolver;
47
+ /** `origin.remote` on forwarded events. Defaults to the endpoint's origin. */
48
+ readonly endpointId?: string;
49
+ }
50
+
51
+ /** The JSON-RPC calls a session proxy makes. Every call sends `A2A-Version: 1.0`. */
52
+ export interface A2ATransport {
53
+ call(method: string, params: JsonObject, signal?: AbortSignal): Promise<unknown>;
54
+ /** One SSE response. It ends when the peer closes it, or quietly at `maxStreamMs`. */
55
+ stream(method: string, params: JsonObject, signal?: AbortSignal): AsyncGenerator<A2AStreamResponse>;
56
+ }
57
+
58
+ const MAX_CARD_BYTES = 1024 * 1024;
59
+ const CARD_TIMEOUT_MS = 30_000;
60
+ const MAX_ERROR_TEXT = 512;
61
+
62
+ const unsupported = (what: string): A2AClientError => new A2AClientError("a2a_unsupported", `${what} is not supported on an A2A agent`);
63
+
64
+ /**
65
+ * Connects to an A2A 1.0 agent over JSON-RPC and returns an `Agent` proxy, usable wherever an `Agent` goes
66
+ * (`agentNode({ agent })`, a host's session loop). One A2A context is one proxy session; one task is one run.
67
+ * Forwarded events carry `origin: { kind: "external", executedBy: "external" }`: the peer ran the work, so no
68
+ * local hook gated it. Every request is DNS-pinned and SSRF-checked (`@arnilo/prism/net`) and byte-bounded.
69
+ */
70
+ export async function connectA2A(endpoint: A2AEndpoint, options: ConnectA2AOptions = {}): Promise<Agent> {
71
+ const limits = resolveA2ALimits(options.limits);
72
+ const allowLoopback = options.allowLoopback === true;
73
+ if (endpoint.token !== undefined && !/^(?:env|keyring):.+$/.test(endpoint.token)) throw new A2ALiteralSecretError("token");
74
+ let url: URL;
75
+ try {
76
+ url = new URL(endpoint.url);
77
+ } catch {
78
+ throw new A2AClientError("a2a_transport", "endpoint url is invalid");
79
+ }
80
+ const allowedOrigins = new Set<string>();
81
+ for (const origin of options.allowedOrigins ?? []) {
82
+ try {
83
+ allowedOrigins.add(new URL(origin).origin);
84
+ } catch {
85
+ throw new A2AClientError("a2a_transport", "allowedOrigins holds an invalid url");
86
+ }
87
+ }
88
+
89
+ const cardUrl = endpoint.card || /agent-card\.json$/.test(url.pathname) ? url : new URL(A2A_CARD_PATH, url.origin);
90
+ const peer: PeerCard = readPeerCard(endpoint.card ?? (await fetchCard(cardUrl, allowLoopback)), cardUrl, allowedOrigins);
91
+ await checkUrl(peer.endpoint, allowLoopback);
92
+
93
+ let token: string | undefined;
94
+ if (endpoint.token !== undefined) {
95
+ const resolver = options.credentials ?? createEnvRefCredentialResolver();
96
+ let secret: { readonly value?: string } | undefined;
97
+ try {
98
+ secret = (await resolver.resolve(endpoint.token, { package: "@arnilo/prism-hosts/a2a" })) as { value?: string } | undefined;
99
+ } catch {
100
+ secret = undefined;
101
+ }
102
+ if (!secret?.value) throw new A2AClientError("a2a_transport", "token reference is unavailable");
103
+ token = secret.value;
104
+ }
105
+ const scrub = (text: string): string => (token ? text.split(token).join("[redacted]") : text);
106
+ const transport = createTransport(peer.endpoint, token, allowLoopback, limits, scrub);
107
+
108
+ const card = peer.card;
109
+ const agentId = card.name;
110
+ const origin: EventOrigin = {
111
+ kind: "external",
112
+ agent: card.name,
113
+ agentId,
114
+ vendor: "a2a",
115
+ remote: options.endpointId ?? peer.endpoint.origin,
116
+ depth: 0,
117
+ executedBy: "external",
118
+ };
119
+ const contexts = new Map<string, A2AContextState>();
120
+ const handles = new Set<A2ASessionHandle>();
121
+ const agentSubscribers = new Set<() => void>();
122
+ let disposed = false;
123
+
124
+ const config = Object.freeze({ id: agentId, name: card.name }) as unknown as Agent["config"];
125
+ const inspection = Object.freeze({
126
+ packages: [],
127
+ tools: [],
128
+ skills: [],
129
+ commands: [],
130
+ hooks: {},
131
+ slots: {},
132
+ store: { owner: "a2a", capabilities: [] },
133
+ disabled: { tools: [], skills: [], commands: [], hooks: [] },
134
+ statusNotes: [],
135
+ a2a: Object.freeze({
136
+ endpoint: peer.endpoint.origin + peer.endpoint.pathname,
137
+ protocolVersion: A2A_PROTOCOL_VERSION,
138
+ streaming: peer.streaming,
139
+ card: Object.freeze({ name: card.name, version: card.version, skills: (card.skills ?? []).map((skill) => skill.id) }),
140
+ }),
141
+ }) as unknown as AgentInspection;
142
+
143
+ const agent: Agent = {
144
+ id: agentId,
145
+ config,
146
+ commands: {
147
+ list() {
148
+ throw unsupported("commands.list()");
149
+ },
150
+ async run() {
151
+ throw unsupported("commands.run()");
152
+ },
153
+ },
154
+ tools: Object.freeze([]) as unknown as Agent["tools"],
155
+ skills: Object.freeze([]) as unknown as Agent["skills"],
156
+ sessions: {
157
+ async list() {
158
+ throw unsupported("sessions.list()");
159
+ },
160
+ async get() {
161
+ throw unsupported("sessions.get()");
162
+ },
163
+ async delete() {
164
+ throw unsupported("sessions.delete()");
165
+ },
166
+ async search() {
167
+ throw unsupported("sessions.search()");
168
+ },
169
+ },
170
+ models: {
171
+ async list() {
172
+ throw unsupported("models.list()");
173
+ },
174
+ resolve() {
175
+ throw unsupported("models.resolve()");
176
+ },
177
+ },
178
+ async reload() {
179
+ throw unsupported("reload()");
180
+ },
181
+ /** `id` is the A2A context id. `parent`, `ownership`, `actor` and `metadata` stay local: A2A has no equivalent. */
182
+ async session(sessionOptions = {}) {
183
+ if (disposed) throw new A2AClientError("a2a_unsupported", "the A2A agent has been disposed");
184
+ const contextId = sessionOptions.id ?? randomUUID();
185
+ if (!isA2AId(contextId)) throw new A2AClientError("a2a_unsupported", "session id must be an A2A context id");
186
+ let state = contexts.get(contextId);
187
+ if (!state) {
188
+ state = { contextId, messages: [] };
189
+ contexts.set(contextId, state);
190
+ }
191
+ const handle = createA2ASession(
192
+ { transport, origin, streaming: peer.streaming, limits, scrub, ...(options.host?.ui ? { ui: options.host.ui } : {}) },
193
+ state,
194
+ () => handles.delete(handle),
195
+ );
196
+ handles.add(handle);
197
+ return handle.session;
198
+ },
199
+ subscribe() {
200
+ // A2A has no agent-scoped events; the iterable ends at `dispose()`.
201
+ let wake: (() => void) | undefined;
202
+ let ended = false;
203
+ const end = () => {
204
+ ended = true;
205
+ wake?.();
206
+ };
207
+ agentSubscribers.add(end);
208
+ return {
209
+ async *[Symbol.asyncIterator](): AsyncGenerator<AgentEvent> {
210
+ try {
211
+ while (!ended && !disposed) {
212
+ await new Promise<void>((resolve) => {
213
+ wake = resolve;
214
+ });
215
+ }
216
+ } finally {
217
+ agentSubscribers.delete(end);
218
+ }
219
+ },
220
+ };
221
+ },
222
+ async dispose() {
223
+ if (disposed) return;
224
+ disposed = true;
225
+ await Promise.all([...handles].map((handle) => handle.dispose()));
226
+ for (const end of agentSubscribers) end();
227
+ agentSubscribers.clear();
228
+ },
229
+ inspect() {
230
+ return inspection;
231
+ },
232
+ };
233
+ return agent;
234
+ }
235
+
236
+ async function checkUrl(url: URL, allowLoopback: boolean): Promise<void> {
237
+ try {
238
+ if (url.username || url.password || url.hash) throw new Error("url must not embed credentials or a fragment");
239
+ const loopback = allowLoopback && isLoopbackHostname(url.hostname);
240
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) throw new Error("url must be https");
241
+ await resolvePinnedAddress(url, defaultResolver, undefined, allowLoopback, undefined, "A2A");
242
+ } catch (error) {
243
+ throw transportError(error, "A2A endpoint is not allowed");
244
+ }
245
+ }
246
+
247
+ async function fetchCard(cardUrl: URL, allowLoopback: boolean): Promise<unknown> {
248
+ let response: Response;
249
+ try {
250
+ response = await pinnedFetch(
251
+ cardUrl,
252
+ { headers: { accept: "application/json" }, signal: AbortSignal.timeout(CARD_TIMEOUT_MS) },
253
+ { errorPrefix: "A2A card", allowLoopback, maxResponseBytes: MAX_CARD_BYTES },
254
+ );
255
+ } catch (error) {
256
+ throw transportError(error, "Agent Card fetch failed");
257
+ }
258
+ if (!response.ok) {
259
+ await response.body?.cancel().catch(() => {});
260
+ throw new A2AClientError("a2a_invalid_card", `Agent Card fetch failed with HTTP ${response.status}`);
261
+ }
262
+ try {
263
+ return JSON.parse(await response.text());
264
+ } catch (error) {
265
+ if (error instanceof SyntaxError) throw new A2AClientError("a2a_invalid_card", "Agent Card is not JSON");
266
+ throw transportError(error, "Agent Card fetch failed");
267
+ }
268
+ }
269
+
270
+ function transportError(error: unknown, fallback: string): A2AClientError {
271
+ if (error instanceof A2AClientError) return error;
272
+ const detail = error instanceof Error ? error.message.slice(0, MAX_ERROR_TEXT) : "";
273
+ return new A2AClientError("a2a_transport", detail ? `${fallback}: ${detail}` : fallback);
274
+ }
275
+
276
+ function createTransport(
277
+ endpoint: URL,
278
+ token: string | undefined,
279
+ allowLoopback: boolean,
280
+ limits: ResolvedA2ALimits,
281
+ scrub: (text: string) => string,
282
+ ): A2ATransport {
283
+ let seq = 0;
284
+
285
+ async function post(
286
+ method: string,
287
+ params: JsonObject,
288
+ accept: string,
289
+ maxBytes: number,
290
+ signal: AbortSignal | undefined,
291
+ ): Promise<Response> {
292
+ const body = JSON.stringify({ jsonrpc: "2.0", id: ++seq, method, params });
293
+ if (Buffer.byteLength(body) > limits.maxRequestBytes) throw new A2AClientError("a2a_transport", "Request exceeds maxRequestBytes");
294
+ const headers: Record<string, string> = { "content-type": "application/json", accept, "a2a-version": A2A_PROTOCOL_VERSION };
295
+ if (token) headers.authorization = `Bearer ${token}`;
296
+ try {
297
+ return await pinnedFetch(
298
+ endpoint,
299
+ { method: "POST", headers, body, ...(signal ? { signal } : {}) },
300
+ {
301
+ errorPrefix: "A2A",
302
+ allowLoopback,
303
+ maxResponseBytes: maxBytes,
304
+ },
305
+ );
306
+ } catch (error) {
307
+ if (signal?.aborted) throw error;
308
+ throw new A2AClientError("a2a_transport", scrub(transportError(error, "A2A request failed").message));
309
+ }
310
+ }
311
+
312
+ /** A JSON-RPC response body: its `result`, or its `error` as an `A2AError`. */
313
+ function unwrap(value: unknown, status: number): unknown {
314
+ if (value === null || typeof value !== "object" || (value as { jsonrpc?: unknown }).jsonrpc !== "2.0") {
315
+ throw new A2AClientError("a2a_invalid_response", `The peer did not answer JSON-RPC (HTTP ${status})`);
316
+ }
317
+ const error = (value as { error?: unknown }).error;
318
+ if (error !== undefined) {
319
+ const code = (error as { code?: unknown } | null)?.code;
320
+ const message = (error as { message?: unknown } | null)?.message;
321
+ throw new A2AError(a2aErrorNameOf(code), scrub(typeof message === "string" ? message.slice(0, MAX_ERROR_TEXT) : "A2A error"), status);
322
+ }
323
+ if (!("result" in value)) throw new A2AClientError("a2a_invalid_response", "The peer answered with no result");
324
+ return (value as { result: unknown }).result;
325
+ }
326
+
327
+ async function readJson(response: Response): Promise<unknown> {
328
+ let text: string;
329
+ try {
330
+ text = await response.text();
331
+ } catch (error) {
332
+ throw new A2AClientError("a2a_transport", scrub(transportError(error, "A2A response failed").message));
333
+ }
334
+ try {
335
+ return JSON.parse(text);
336
+ } catch {
337
+ throw new A2AClientError("a2a_invalid_response", `The peer did not answer JSON (HTTP ${response.status})`);
338
+ }
339
+ }
340
+
341
+ return {
342
+ async call(method, params, signal) {
343
+ const response = await post(method, params, "application/json", limits.maxResponseBytes, signal);
344
+ return unwrap(await readJson(response), response.status);
345
+ },
346
+
347
+ async *stream(method, params, signal) {
348
+ const local = new AbortController();
349
+ const onAbort = () => local.abort(signal?.reason);
350
+ if (signal?.aborted) local.abort(signal.reason);
351
+ else signal?.addEventListener("abort", onAbort, { once: true });
352
+ let timedOut = false;
353
+ const timer = setTimeout(() => {
354
+ timedOut = true;
355
+ local.abort(new Error("A2A stream reached maxStreamMs"));
356
+ }, limits.maxStreamMs);
357
+ try {
358
+ const response = await post(method, params, "text/event-stream", limits.maxStreamBytes, local.signal);
359
+ const type = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
360
+ if (type !== "text/event-stream") {
361
+ unwrap(await readJson(response), response.status);
362
+ throw new A2AClientError("a2a_invalid_response", "The peer did not answer with an event stream");
363
+ }
364
+ if (!response.body) return;
365
+ const reader = response.body.getReader();
366
+ const decoder = new TextDecoder();
367
+ let buffer = "";
368
+ let count = 0;
369
+ try {
370
+ while (true) {
371
+ let next: ReadableStreamReadResult<Uint8Array>;
372
+ try {
373
+ next = await reader.read();
374
+ } catch (error) {
375
+ if (timedOut) return;
376
+ if (signal?.aborted) throw error;
377
+ throw new A2AClientError("a2a_transport", scrub(transportError(error, "A2A stream failed").message));
378
+ }
379
+ if (next.done) return;
380
+ buffer += decoder.decode(next.value, { stream: true });
381
+ let boundary = buffer.search(/\r?\n\r?\n/);
382
+ while (boundary >= 0) {
383
+ const block = buffer.slice(0, boundary);
384
+ buffer = buffer.slice(boundary).replace(/^\r?\n\r?\n/, "");
385
+ const data = block
386
+ .split(/\r?\n/)
387
+ .filter((line) => line.startsWith("data:"))
388
+ .map((line) => line.slice(5).replace(/^ /, ""))
389
+ .join("\n");
390
+ if (data.length > 0) {
391
+ if (++count > limits.maxStreamEvents) throw new A2AClientError("a2a_transport", "Stream exceeds maxStreamEvents");
392
+ let parsed: unknown;
393
+ try {
394
+ parsed = JSON.parse(data);
395
+ } catch {
396
+ throw new A2AClientError("a2a_invalid_response", "The peer sent a frame that is not JSON");
397
+ }
398
+ yield parseA2AStreamResponse(unwrap(parsed, response.status), limits.maxParts);
399
+ }
400
+ boundary = buffer.search(/\r?\n\r?\n/);
401
+ }
402
+ }
403
+ } finally {
404
+ await reader.cancel().catch(() => {});
405
+ }
406
+ } catch (error) {
407
+ if (timedOut && !signal?.aborted) return;
408
+ throw error;
409
+ } finally {
410
+ clearTimeout(timer);
411
+ signal?.removeEventListener("abort", onAbort);
412
+ }
413
+ },
414
+ };
415
+ }
@@ -0,0 +1,87 @@
1
+ /** A2A 1.0 JSON-RPC error codes (spec §5.4) plus the standard JSON-RPC 2.0 codes. */
2
+ export const A2A_ERROR_CODES = {
3
+ parseError: -32700,
4
+ invalidRequest: -32600,
5
+ methodNotFound: -32601,
6
+ invalidParams: -32602,
7
+ internalError: -32603,
8
+ /** Implementation-defined (JSON-RPC server-error range): a bound on concurrent tasks or contexts was hit. */
9
+ overloaded: -32000,
10
+ taskNotFound: -32001,
11
+ taskNotCancelable: -32002,
12
+ pushNotificationNotSupported: -32003,
13
+ unsupportedOperation: -32004,
14
+ contentTypeNotSupported: -32005,
15
+ invalidAgentResponse: -32006,
16
+ extendedAgentCardNotConfigured: -32007,
17
+ extensionSupportRequired: -32008,
18
+ versionNotSupported: -32009,
19
+ } as const;
20
+
21
+ export type A2AErrorName = keyof typeof A2A_ERROR_CODES;
22
+
23
+ /** A protocol error answered as a JSON-RPC `error`. The message is fixed text, never caller or secret data. */
24
+ export class A2AError extends Error {
25
+ readonly code: number;
26
+ readonly errorName: A2AErrorName;
27
+ /** HTTP status of the response that carries this error. JSON-RPC errors ride a 200 unless the transport itself failed. */
28
+ readonly status: number;
29
+
30
+ constructor(name: A2AErrorName, message: string, status = 200) {
31
+ super(message);
32
+ this.name = "A2AError";
33
+ this.errorName = name;
34
+ this.code = A2A_ERROR_CODES[name];
35
+ this.status = status;
36
+ }
37
+ }
38
+
39
+ /** Invalid `serveA2A` / `connectA2A` options, thrown at construction. */
40
+ export class A2AConfigError extends Error {
41
+ readonly code = "ERR_PRISM_A2A_CONFIG";
42
+ constructor(message: string) {
43
+ super(message);
44
+ this.name = "A2AConfigError";
45
+ }
46
+ }
47
+
48
+ /** The `A2AErrorName` for a wire error code; an unknown code reads as `internalError`. */
49
+ export function a2aErrorNameOf(code: unknown): A2AErrorName {
50
+ for (const [name, value] of Object.entries(A2A_ERROR_CODES)) if (value === code) return name as A2AErrorName;
51
+ return "internalError";
52
+ }
53
+
54
+ export type A2AClientErrorCode =
55
+ /** A proxy member with no A2A equivalent (`commands`, `reload`, `models`, `fork`, …). */
56
+ | "a2a_unsupported"
57
+ /** The peer's Agent Card is malformed, or its endpoint is on an origin the host did not allow. */
58
+ | "a2a_invalid_card"
59
+ /** The URL failed the SSRF checks, the connection failed, or a byte or time bound was hit. */
60
+ | "a2a_transport"
61
+ /** The peer answered something that is not A2A 1.0. */
62
+ | "a2a_invalid_response"
63
+ /** The session already has a run in progress. */
64
+ | "a2a_busy"
65
+ /** `resume` on a session with no task waiting for decisions in this process. */
66
+ | "a2a_no_pending_task";
67
+
68
+ /** A `connectA2A` proxy failure. The message is fixed or bounded text and never holds the token. */
69
+ export class A2AClientError extends Error {
70
+ readonly code: A2AClientErrorCode;
71
+ constructor(code: A2AClientErrorCode, message: string) {
72
+ super(message);
73
+ this.name = "A2AClientError";
74
+ this.code = code;
75
+ }
76
+ }
77
+
78
+ export const A2A_LITERAL_SECRET_CODE = "ERR_PRISM_A2A_LITERAL_SECRET";
79
+
80
+ /** A credential option held a literal secret instead of an `env:` / `keyring:` ref. */
81
+ export class A2ALiteralSecretError extends Error {
82
+ readonly code = A2A_LITERAL_SECRET_CODE;
83
+ constructor(field: string) {
84
+ super(`${field} must be an env: or keyring: reference, not a literal secret`);
85
+ this.name = "A2ALiteralSecretError";
86
+ }
87
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `@arnilo/prism-hosts/a2a`: A2A 1.0 interop for one Prism `Agent` over JSON-RPC.
3
+ * `serveA2A` serves the agent to A2A peers; `connectA2A` returns an `Agent` proxy for a remote A2A agent. Importing this module opens no socket and starts no timer.
4
+ */
5
+ export type {
6
+ A2AAgentCapabilities,
7
+ A2AAgentCard,
8
+ A2AAgentCardSignature,
9
+ A2AAgentExtension,
10
+ A2AAgentInterface,
11
+ A2AAgentSkill,
12
+ } from "./card.js";
13
+ export { type A2AEndpoint, type ConnectA2AOptions, connectA2A } from "./connect.js";
14
+ export {
15
+ A2A_CARD_PATH,
16
+ A2A_PROTOCOL_VERSION,
17
+ type A2AArtifact,
18
+ type A2AMessage,
19
+ type A2APart,
20
+ type A2ARole,
21
+ type A2AStreamResponse,
22
+ type A2ATask,
23
+ type A2ATaskArtifactUpdateEvent,
24
+ type A2ATaskState,
25
+ type A2ATaskStatus,
26
+ type A2ATaskStatusUpdateEvent,
27
+ PRISM_DECISIONS_EXTENSION,
28
+ } from "./codec.js";
29
+ export {
30
+ A2A_ERROR_CODES,
31
+ A2A_LITERAL_SECRET_CODE,
32
+ A2AClientError,
33
+ type A2AClientErrorCode,
34
+ A2AConfigError,
35
+ A2AError,
36
+ type A2AErrorName,
37
+ A2ALiteralSecretError,
38
+ } from "./errors.js";
39
+ export { A2A_LIMITS, type A2ALimitName, type A2ALimitOptions, type ResolvedA2ALimits } from "./limits.js";
40
+ export { type A2AAuthorization, type A2AAuthorizeInput, type A2AHandler, type ServeA2AOptions, serveA2A } from "./serve.js";
@@ -0,0 +1,43 @@
1
+ import { A2AConfigError } from "./errors.js";
2
+
3
+ /** Defaults. The host sets each (`limits`); its value is the cap (plan 239 Task 5). Starting point: 0.12's caps. */
4
+ export const A2A_LIMITS = {
5
+ /** Bytes of one JSON-RPC request body. */
6
+ maxRequestBytes: 64 * 1024,
7
+ /** Bytes of one non-streaming JSON-RPC response body. */
8
+ maxResponseBytes: 1024 * 1024,
9
+ /** Bytes of one SSE response. */
10
+ maxStreamBytes: 10 * 1024 * 1024,
11
+ /** Frames on one SSE response. */
12
+ maxStreamEvents: 10_000,
13
+ /** Wall-clock length of one SSE response; the task keeps running and can be resubscribed. */
14
+ maxStreamMs: 120_000,
15
+ /** Wall-clock length of one task segment (a run or a resume); past it the run is aborted and the task fails. */
16
+ taskTimeoutMs: 120_000,
17
+ /** `TASK_STATE_WORKING` tasks one principal may hold at once. */
18
+ maxConcurrentTasks: 16,
19
+ /** Tasks the in-process registry keeps; the oldest settled one is evicted first. */
20
+ maxTasks: 1_024,
21
+ /** Contexts (open sessions) kept at once; the least recently used idle one is closed first. */
22
+ maxContexts: 256,
23
+ /** Parts in one inbound message. */
24
+ maxParts: 32,
25
+ /** Messages a `GetTask` `historyLength` may return. */
26
+ maxHistory: 100,
27
+ } as const;
28
+
29
+ export type A2ALimitName = keyof typeof A2A_LIMITS;
30
+ export type A2ALimitOptions = { readonly [K in A2ALimitName]?: number };
31
+ export type ResolvedA2ALimits = { readonly [K in A2ALimitName]: number };
32
+
33
+ export function resolveA2ALimits(options: A2ALimitOptions = {}): ResolvedA2ALimits {
34
+ const resolved = {} as Record<A2ALimitName, number>;
35
+ for (const name of Object.keys(A2A_LIMITS) as A2ALimitName[]) {
36
+ const value = options[name] ?? A2A_LIMITS[name];
37
+ if (!Number.isSafeInteger(value) || value < 1) {
38
+ throw new A2AConfigError(`limits.${name} must be a positive safe integer`);
39
+ }
40
+ resolved[name] = value;
41
+ }
42
+ return resolved;
43
+ }
@@ -0,0 +1,28 @@
1
+ import { type PendingDecision, parseSuspendedRunEntry, type SessionEntry } from "@arnilo/prism";
2
+
3
+ // Third copy of this tip rule (remote/src/pending.ts, headless/src/pending.ts); see plan 236 Further Actions.
4
+
5
+ /**
6
+ * The suspension a session's branch is waiting on, with its run id. `pendingSuspensionOf` is not public, so
7
+ * this applies its tip rule over the public `parseSuspendedRunEntry`: skip `package_state`, then the newest
8
+ * entry must be a `suspended_run`. Anything appended after it means the suspension was resolved or abandoned.
9
+ * A malformed entry yields nothing, so it never resumes.
10
+ */
11
+ export function suspensionOf(
12
+ branch: readonly SessionEntry[],
13
+ ): { readonly runId: string; readonly pending: readonly PendingDecision[] } | undefined {
14
+ for (let index = branch.length - 1; index >= 0; index -= 1) {
15
+ const entry = branch[index];
16
+ if (!entry) continue;
17
+ if (entry.kind === "package_state") continue;
18
+ if (entry.kind !== "suspended_run") return undefined;
19
+ try {
20
+ const parsed = parseSuspendedRunEntry(entry);
21
+ const pending = parsed.interruption.pendingDecisions ?? [];
22
+ return pending.length === 0 ? undefined : { runId: parsed.runId, pending };
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ return undefined;
28
+ }