@arnilo/prism-hosts 0.13.1 → 0.14.1

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 +6 -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 +1276 -1365
  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,526 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type {
3
+ AgentEvent,
4
+ ContentBlock,
5
+ Decision,
6
+ ErrorInfo,
7
+ EventOrigin,
8
+ HostUi,
9
+ HostUiRequest,
10
+ HostUiResponse,
11
+ JsonObject,
12
+ Message,
13
+ PendingDecision,
14
+ RunOptions,
15
+ RunResult,
16
+ Session,
17
+ } from "@arnilo/prism";
18
+ import type { A2ATransport } from "./connect.js";
19
+ import {
20
+ type A2AMessage,
21
+ type A2APart,
22
+ type A2AStreamResponse,
23
+ type A2ATaskState,
24
+ decisionsMessage,
25
+ INTERRUPTED_STATES,
26
+ parseA2AStreamResponse,
27
+ parseA2ATask,
28
+ partsText,
29
+ readPendingParts,
30
+ TERMINAL_STATES,
31
+ } from "./codec.js";
32
+ import { A2AClientError, A2AError } from "./errors.js";
33
+ import type { ResolvedA2ALimits } from "./limits.js";
34
+
35
+ type Input = string | Message | readonly Message[];
36
+ type SubscribeArgs = NonNullable<Parameters<Session["subscribe"]>[0]>;
37
+
38
+ /** Per context id, shared by every proxy session opened on it in this process. */
39
+ export interface A2AContextState {
40
+ readonly contextId: string;
41
+ /** The task waiting for decisions, if any. */
42
+ task?: { readonly id: string; readonly pending: readonly PendingDecision[] };
43
+ /** The local transcript: inputs sent and replies received. A2A keeps the peer's history on the peer. */
44
+ readonly messages: Message[];
45
+ }
46
+
47
+ export interface A2AProxyEnv {
48
+ readonly transport: A2ATransport;
49
+ readonly origin: EventOrigin;
50
+ readonly streaming: boolean;
51
+ readonly limits: ResolvedA2ALimits;
52
+ readonly scrub: (text: string) => string;
53
+ readonly ui?: HostUi;
54
+ }
55
+
56
+ export interface A2ASessionHandle {
57
+ readonly session: Session;
58
+ dispose(): Promise<void>;
59
+ }
60
+
61
+ const DEFAULT_QUEUE = 1024;
62
+ const POLL_MS = 1_000;
63
+ const CANCEL_TIMEOUT_MS = 5_000;
64
+
65
+ const unsupported = (what: string): A2AClientError => new A2AClientError("a2a_unsupported", `${what} is not supported on an A2A session`);
66
+
67
+ interface Final {
68
+ readonly state: A2ATaskState;
69
+ readonly message?: A2AMessage;
70
+ }
71
+
72
+ interface ActiveRun {
73
+ readonly controller: AbortController;
74
+ taskId?: string;
75
+ final?: Final;
76
+ canceled: boolean;
77
+ timedOut: boolean;
78
+ }
79
+
80
+ /** A bounded subscriber queue; a full queue ends the subscription. */
81
+ function subscriber(maxQueued: number, onReturn: () => void) {
82
+ const queue: AgentEvent[] = [];
83
+ let wake: (() => void) | undefined;
84
+ let ended = false;
85
+ return {
86
+ push(event: AgentEvent) {
87
+ if (ended) return;
88
+ if (queue.length >= maxQueued) ended = true;
89
+ else queue.push(event);
90
+ wake?.();
91
+ },
92
+ end() {
93
+ ended = true;
94
+ wake?.();
95
+ },
96
+ get ended() {
97
+ return ended;
98
+ },
99
+ async *[Symbol.asyncIterator](): AsyncGenerator<AgentEvent> {
100
+ try {
101
+ while (true) {
102
+ const next = queue.shift();
103
+ if (next) {
104
+ yield next;
105
+ continue;
106
+ }
107
+ if (ended) return;
108
+ await new Promise<void>((resolve) => {
109
+ wake = resolve;
110
+ });
111
+ wake = undefined;
112
+ }
113
+ } finally {
114
+ ended = true;
115
+ onReturn();
116
+ }
117
+ },
118
+ };
119
+ }
120
+
121
+ type Subscriber = ReturnType<typeof subscriber> & { readonly acrossRuns: boolean };
122
+
123
+ /** Maps a Prism input to the parts of one A2A user message. Media must be inline base64. */
124
+ function inputParts(input: Input, maxParts: number): { parts: A2APart[]; message: Message } {
125
+ if (typeof input === "string") return { parts: [{ text: input }], message: { role: "user", content: [{ type: "text", text: input }] } };
126
+ const messages: readonly Message[] = Array.isArray(input) ? input : [input as Message];
127
+ const parts: A2APart[] = [];
128
+ const content: ContentBlock[] = [];
129
+ for (const message of messages) {
130
+ if (message.role !== "user") throw new A2AClientError("a2a_unsupported", "only user messages can be sent to an A2A agent");
131
+ for (const block of message.content) {
132
+ content.push(block);
133
+ if (block.type === "text") parts.push({ text: block.text });
134
+ else if (block.type === "image" && typeof block.data === "string") {
135
+ parts.push({ raw: block.data, mediaType: block.mimeType, ...(block.name ? { filename: block.name } : {}) });
136
+ } else if ((block.type === "file" || block.type === "document" || block.type === "audio") && typeof block.data === "string") {
137
+ parts.push({ raw: block.data, mediaType: block.mediaType, ...(block.name ? { filename: block.name } : {}) });
138
+ } else throw new A2AClientError("a2a_unsupported", `a ${block.type} block cannot be sent to an A2A agent`);
139
+ }
140
+ }
141
+ if (parts.length === 0 || parts.length > maxParts) throw new A2AClientError("a2a_unsupported", "input must hold 1 to maxParts parts");
142
+ return { parts, message: { role: "user", content } };
143
+ }
144
+
145
+ function requestFor(sessionId: string, pending: PendingDecision): HostUiRequest {
146
+ if (pending.kind === "elicitation") {
147
+ return {
148
+ kind: "input",
149
+ sessionId,
150
+ title: pending.reason,
151
+ ...(pending.elicitationSchema ? { detail: JSON.stringify(pending.elicitationSchema) } : {}),
152
+ };
153
+ }
154
+ return { kind: "confirm", sessionId, title: `Approve ${pending.scope.toolName ?? "tool call"}`, detail: pending.reason };
155
+ }
156
+
157
+ /** A host answer as a decision, or `undefined` to leave it pending (the run then suspends). */
158
+ function decisionFrom(pending: PendingDecision, answer: HostUiResponse): Decision | undefined {
159
+ if (answer.status === "unavailable") return undefined;
160
+ if (pending.kind === "elicitation") {
161
+ if (answer.status !== "answered" || typeof answer.value !== "string") return undefined;
162
+ try {
163
+ const parsed: unknown = JSON.parse(answer.value);
164
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
165
+ return { approvalId: pending.approvalId, outcome: "allow_once", elicitation: parsed as JsonObject };
166
+ } catch {
167
+ return undefined;
168
+ }
169
+ }
170
+ if (answer.status === "dismissed") return { approvalId: pending.approvalId, outcome: "reject_once" };
171
+ if (typeof answer.value !== "boolean") return undefined;
172
+ return { approvalId: pending.approvalId, outcome: answer.value ? "allow_once" : "reject_once" };
173
+ }
174
+
175
+ /**
176
+ * The proxy `Session` for one A2A context. `run`/`stream` send one message and follow the task it starts;
177
+ * `resume` answers a `TASK_STATE_INPUT_REQUIRED` task; `abort` sends `CancelTask`. Members with no A2A
178
+ * equivalent throw `A2AClientError` (`a2a_unsupported`).
179
+ */
180
+ export function createA2ASession(env: A2AProxyEnv, state: A2AContextState, onClose: () => void): A2ASessionHandle {
181
+ const { transport, limits, scrub } = env;
182
+ const sessionId = state.contextId;
183
+ const subscribers = new Set<Subscriber>();
184
+ let active: ActiveRun | undefined;
185
+ let closed = false;
186
+
187
+ const closeSubscribers = (onlyRunScoped: boolean) => {
188
+ for (const entry of [...subscribers]) {
189
+ if (onlyRunScoped && entry.acrossRuns) continue;
190
+ entry.end();
191
+ subscribers.delete(entry);
192
+ }
193
+ };
194
+
195
+ const tag = (event: Record<string, unknown>): AgentEvent => ({ ...event, origin: env.origin }) as unknown as AgentEvent;
196
+
197
+ async function cancelRemote(taskId: string): Promise<void> {
198
+ await transport.call("CancelTask", { id: taskId }, AbortSignal.timeout(CANCEL_TIMEOUT_MS)).catch(() => undefined);
199
+ }
200
+
201
+ /** Re-reads a task whose stream ended before a final state: `GetTask`, then `SubscribeToTask` (or a poll). */
202
+ async function* recover(taskId: string, signal: AbortSignal): AsyncGenerator<A2AStreamResponse> {
203
+ const task = parseA2ATask(await transport.call("GetTask", { id: taskId }, signal), limits.maxParts);
204
+ yield { task };
205
+ if (TERMINAL_STATES.has(task.status.state) || INTERRUPTED_STATES.has(task.status.state)) return;
206
+ if (env.streaming) {
207
+ try {
208
+ yield* transport.stream("SubscribeToTask", { id: taskId }, signal);
209
+ } catch (error) {
210
+ // The task ended between the two calls: the next round reads it with `GetTask`.
211
+ if (!(error instanceof A2AError && error.errorName === "unsupportedOperation")) throw error;
212
+ }
213
+ return;
214
+ }
215
+ await new Promise<void>((resolve) => {
216
+ const timer = setTimeout(resolve, POLL_MS);
217
+ signal.addEventListener(
218
+ "abort",
219
+ () => {
220
+ clearTimeout(timer);
221
+ resolve();
222
+ },
223
+ { once: true },
224
+ );
225
+ });
226
+ }
227
+
228
+ function send(message: A2AMessage, signal: AbortSignal): AsyncIterable<A2AStreamResponse> {
229
+ const params = { message: message as unknown as JsonObject };
230
+ if (env.streaming) return transport.stream("SendStreamingMessage", params, signal);
231
+ return (async function* () {
232
+ const result = await transport.call("SendMessage", params, signal);
233
+ const value = result !== null && typeof result === "object" && "status" in result && "id" in result ? { task: result } : result;
234
+ yield parseA2AStreamResponse(value, limits.maxParts);
235
+ })();
236
+ }
237
+
238
+ async function* drive(
239
+ kickoff: { message: A2AMessage; user?: Message; resumed: boolean },
240
+ options: RunOptions | undefined,
241
+ sink: (result: RunResult) => void,
242
+ ): AsyncGenerator<AgentEvent> {
243
+ if (closed) throw new A2AClientError("a2a_unsupported", "the session is closed");
244
+ if (active) throw new A2AClientError("a2a_busy", "session already has a run in progress");
245
+ const run: ActiveRun = { controller: new AbortController(), canceled: false, timedOut: false };
246
+ active = run;
247
+ const signal = run.controller.signal;
248
+ const external = options?.signal;
249
+ const onExternalAbort = () => {
250
+ run.canceled = true;
251
+ run.controller.abort(external?.reason);
252
+ };
253
+ if (external?.aborted) onExternalAbort();
254
+ else external?.addEventListener("abort", onExternalAbort, { once: true });
255
+ const timer = setTimeout(() => {
256
+ run.timedOut = true;
257
+ run.controller.abort(new Error("A2A task reached taskTimeoutMs"));
258
+ }, limits.taskTimeoutMs);
259
+
260
+ const appended: Message[] = kickoff.user ? [kickoff.user] : [];
261
+ if (kickoff.user) state.messages.push(kickoff.user);
262
+ let text = "";
263
+ let runId: string | undefined;
264
+ let failure: ErrorInfo | undefined;
265
+ const emit = (event: AgentEvent): AgentEvent => {
266
+ for (const entry of subscribers) entry.push(event);
267
+ return event;
268
+ };
269
+ const appendText = (chunk: string): string => {
270
+ const clean = scrub(chunk);
271
+ if (text.length + clean.length <= limits.maxResponseBytes) text += clean;
272
+ return clean;
273
+ };
274
+
275
+ try {
276
+ let frames: AsyncIterable<A2AStreamResponse> = send(kickoff.message, signal);
277
+ while (true) {
278
+ for await (const frame of frames) {
279
+ if ("task" in frame) {
280
+ run.taskId ??= frame.task.id;
281
+ const status = frame.task.status;
282
+ if ((TERMINAL_STATES.has(status.state) || INTERRUPTED_STATES.has(status.state)) && text.length === 0) {
283
+ for (const artifact of frame.task.artifacts ?? []) appendText(partsText(artifact.parts));
284
+ }
285
+ if (TERMINAL_STATES.has(status.state) || INTERRUPTED_STATES.has(status.state)) {
286
+ run.final = { state: status.state, ...(status.message ? { message: status.message } : {}) };
287
+ }
288
+ } else if ("statusUpdate" in frame) {
289
+ run.taskId ??= frame.statusUpdate.taskId;
290
+ const status = frame.statusUpdate.status;
291
+ if (TERMINAL_STATES.has(status.state) || INTERRUPTED_STATES.has(status.state)) {
292
+ run.final = { state: status.state, ...(status.message ? { message: status.message } : {}) };
293
+ }
294
+ } else if ("message" in frame) {
295
+ // A message-only reply: the peer answered without a task.
296
+ appendText(partsText(frame.message.parts));
297
+ run.final = { state: "TASK_STATE_COMPLETED" };
298
+ }
299
+ if (runId === undefined) {
300
+ runId = run.taskId ?? `a2a-message-${randomUUID()}`;
301
+ yield emit(tag({ type: "run.started", sessionId, runId, ...(kickoff.resumed ? { resumed: true } : {}) }));
302
+ }
303
+ if ("artifactUpdate" in frame) {
304
+ const chunk = appendText(partsText(frame.artifactUpdate.artifact.parts));
305
+ if (chunk.length > 0) yield emit(tag({ type: "message.delta", sessionId, runId, content: { type: "text", text: chunk } }));
306
+ }
307
+ if (run.final) break;
308
+ }
309
+ if (run.final?.state === "TASK_STATE_INPUT_REQUIRED" && env.ui && run.taskId) {
310
+ const decisions = await askHost(env.ui, sessionId, readPendingParts(run.final.message));
311
+ if (decisions) {
312
+ run.final = undefined;
313
+ frames = send(decisionsMessage(randomUUID(), run.taskId, sessionId, decisions), signal);
314
+ continue;
315
+ }
316
+ }
317
+ if (run.final) break;
318
+ if (!run.taskId) throw new A2AClientError("a2a_invalid_response", "The peer ended the response before naming a task");
319
+ signal.throwIfAborted();
320
+ frames = recover(run.taskId, signal);
321
+ }
322
+ } catch (error) {
323
+ if (run.canceled || run.timedOut) {
324
+ if (run.taskId) await cancelRemote(run.taskId);
325
+ } else if (error instanceof A2AError) {
326
+ failure = { name: "A2AError", code: error.code, message: scrub(error.message) };
327
+ } else if (error instanceof A2AClientError) {
328
+ failure = { name: "A2AClientError", code: error.code, message: scrub(error.message) };
329
+ } else {
330
+ failure = { name: "A2AClientError", code: "a2a_transport", message: "A2A request failed" };
331
+ }
332
+ } finally {
333
+ clearTimeout(timer);
334
+ external?.removeEventListener("abort", onExternalAbort);
335
+ }
336
+
337
+ runId ??= run.taskId ?? `a2a-failed-${randomUUID()}`;
338
+ let message: Message | undefined;
339
+ if (text.length > 0) {
340
+ message = { role: "assistant", content: [{ type: "text", text }] };
341
+ appended.push(message);
342
+ state.messages.push(message);
343
+ yield emit(tag({ type: "message.completed", sessionId, runId, message }));
344
+ }
345
+ const base = { sessionId, runId, text, content: message?.content ?? [], ...(message ? { message } : {}), messages: appended };
346
+ let result: RunResult;
347
+ state.task = undefined;
348
+ const finalState = run.canceled ? "TASK_STATE_CANCELED" : run.timedOut || failure ? undefined : run.final?.state;
349
+ const statusText = run.final?.message ? scrub(partsText(run.final.message.parts)).slice(0, 2048) : "";
350
+ if (finalState === "TASK_STATE_COMPLETED") {
351
+ result = { ...base, status: "completed" };
352
+ yield emit(tag({ type: "run.completed", sessionId, runId, status: "completed" }));
353
+ } else if (finalState === "TASK_STATE_REJECTED") {
354
+ result = { ...base, status: "stopped", stopReason: "denied" };
355
+ yield emit(tag({ type: "run.completed", sessionId, runId, status: "stopped", stopReason: "denied" }));
356
+ } else if (finalState === "TASK_STATE_CANCELED") {
357
+ const error: ErrorInfo = { name: "AbortError", code: "aborted", message: "The A2A task was canceled" };
358
+ result = { ...base, status: "aborted", error, abortReason: "aborted" };
359
+ yield emit(tag({ type: "run.failed", sessionId, runId, error }));
360
+ } else if (finalState === "TASK_STATE_INPUT_REQUIRED" && readPendingParts(run.final?.message).length > 0) {
361
+ const pending = readPendingParts(run.final?.message).map((decision) => ({ ...decision, reason: scrub(decision.reason) }));
362
+ state.task = { id: run.taskId as string, pending };
363
+ const first = pending[0] as PendingDecision;
364
+ result = { ...base, status: "suspended", pending };
365
+ yield emit(
366
+ tag({
367
+ type: "run.suspended",
368
+ sessionId,
369
+ runId,
370
+ version: 1,
371
+ interruption: {
372
+ kind: first.kind === "elicitation" ? "elicitation" : "tool_approval",
373
+ reason: first.reason,
374
+ ...(first.scope.toolName ? { toolName: first.scope.toolName } : {}),
375
+ pendingDecisions: pending,
376
+ },
377
+ }),
378
+ );
379
+ } else {
380
+ const error: ErrorInfo =
381
+ failure ??
382
+ (run.timedOut
383
+ ? { name: "A2AClientError", code: "a2a_timeout", message: "The A2A task reached taskTimeoutMs" }
384
+ : finalState === "TASK_STATE_AUTH_REQUIRED"
385
+ ? { name: "A2AClientError", code: "a2a_auth_required", message: "The A2A agent requires more authentication" }
386
+ : finalState === "TASK_STATE_INPUT_REQUIRED"
387
+ ? { name: "A2AClientError", code: "a2a_invalid_response", message: "The A2A task asked for input it did not describe" }
388
+ : { name: "A2AClientError", code: "a2a_task_failed", message: statusText || "The A2A task failed" });
389
+ result = { ...base, status: "failed", error };
390
+ yield emit(tag({ type: "run.failed", sessionId, runId, error }));
391
+ }
392
+ if (active === run) active = undefined;
393
+ closeSubscribers(true);
394
+ sink(result);
395
+ }
396
+
397
+ /** Wraps `drive` so a consumer that stops early cancels the remote task. */
398
+ function owned(
399
+ kickoff: Parameters<typeof drive>[0],
400
+ options: RunOptions | undefined,
401
+ sink: (result: RunResult) => void,
402
+ ): AsyncGenerator<AgentEvent> {
403
+ const inner = drive(kickoff, options, sink);
404
+ let done = false;
405
+ return (async function* () {
406
+ try {
407
+ for await (const event of inner) yield event;
408
+ done = true;
409
+ } finally {
410
+ if (!done && active) {
411
+ const run = active;
412
+ run.canceled = true;
413
+ run.controller.abort(new Error("A2A stream consumer stopped"));
414
+ // Drain so the remote task is canceled and the run settles.
415
+ for await (const _ of inner) {
416
+ // discard
417
+ }
418
+ }
419
+ }
420
+ })();
421
+ }
422
+
423
+ function sendInput(input: Input, options: RunOptions | undefined, sink: (result: RunResult) => void): AsyncGenerator<AgentEvent> {
424
+ const { parts, message } = inputParts(input, limits.maxParts);
425
+ return owned(
426
+ { message: { messageId: randomUUID(), role: "ROLE_USER", contextId: sessionId, parts }, user: message, resumed: false },
427
+ options,
428
+ sink,
429
+ );
430
+ }
431
+
432
+ const session: Session = {
433
+ id: sessionId,
434
+ leafId: undefined,
435
+ async run(input: Input, options?: RunOptions) {
436
+ let result: RunResult | undefined;
437
+ for await (const _ of sendInput(input, options, (value) => {
438
+ result = value;
439
+ })) {
440
+ // events go to subscribers
441
+ }
442
+ return result as RunResult;
443
+ },
444
+ stream: (input: Input, options) => sendInput(input, options, () => {}),
445
+ resume(decisions: readonly Decision[], options) {
446
+ const task = state.task;
447
+ if (!task) throw new A2AClientError("a2a_no_pending_task", "no A2A task in this context is waiting for decisions");
448
+ return owned({ message: decisionsMessage(randomUUID(), task.id, sessionId, decisions), resumed: true }, options, () => {});
449
+ },
450
+ async continue() {
451
+ throw unsupported("continue()");
452
+ },
453
+ continueStream() {
454
+ throw unsupported("continueStream()");
455
+ },
456
+ steer() {
457
+ throw unsupported("steer()");
458
+ },
459
+ abort() {
460
+ if (!active) return;
461
+ active.canceled = true;
462
+ active.controller.abort(new Error("A2A session aborted"));
463
+ },
464
+ subscribe(options?: SubscribeArgs) {
465
+ const entry: Subscriber = Object.assign(
466
+ subscriber(options?.maxQueuedEvents ?? DEFAULT_QUEUE, () => {
467
+ subscribers.delete(entry);
468
+ }),
469
+ { acrossRuns: options?.acrossRuns === true },
470
+ );
471
+ subscribers.add(entry);
472
+ return entry;
473
+ },
474
+ async close() {
475
+ closed = true;
476
+ closeSubscribers(false);
477
+ onClose();
478
+ },
479
+ async messages() {
480
+ return [...state.messages];
481
+ },
482
+ async entries() {
483
+ throw unsupported("entries()");
484
+ },
485
+ async compact() {
486
+ throw unsupported("compact()");
487
+ },
488
+ async checkout() {
489
+ throw unsupported("checkout()");
490
+ },
491
+ async fork() {
492
+ throw unsupported("fork()");
493
+ },
494
+ contextMeter() {
495
+ throw unsupported("contextMeter()");
496
+ },
497
+ async limits() {
498
+ throw unsupported("limits()");
499
+ },
500
+ };
501
+
502
+ return {
503
+ session,
504
+ async dispose() {
505
+ session.abort();
506
+ await session.close();
507
+ },
508
+ };
509
+ }
510
+
511
+ async function askHost(ui: HostUi, sessionId: string, pending: readonly PendingDecision[]): Promise<Decision[] | undefined> {
512
+ if (pending.length === 0) return undefined;
513
+ const decisions: Decision[] = [];
514
+ for (const decision of pending) {
515
+ let answer: HostUiResponse;
516
+ try {
517
+ answer = await ui.request(requestFor(sessionId, decision));
518
+ } catch {
519
+ return undefined;
520
+ }
521
+ const mapped = decisionFrom(decision, answer);
522
+ if (!mapped) return undefined;
523
+ decisions.push(mapped);
524
+ }
525
+ return decisions;
526
+ }