@providerkit/agents 0.1.0 → 0.2.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 (291) hide show
  1. package/LICENSE-APACHE-2.0 +202 -0
  2. package/README.md +2108 -52
  3. package/THIRD_PARTY_NOTICES.md +521 -0
  4. package/dist/a2a/auth.d.ts +10 -0
  5. package/dist/a2a/auth.d.ts.map +1 -0
  6. package/dist/a2a/auth.js +52 -0
  7. package/dist/a2a/auth.js.map +1 -0
  8. package/dist/a2a/client.d.ts +74 -0
  9. package/dist/a2a/client.d.ts.map +1 -0
  10. package/dist/a2a/client.js +601 -0
  11. package/dist/a2a/client.js.map +1 -0
  12. package/dist/a2a/index.d.ts +22 -0
  13. package/dist/a2a/index.d.ts.map +1 -0
  14. package/dist/a2a/index.js +11 -0
  15. package/dist/a2a/index.js.map +1 -0
  16. package/dist/a2a/memory-runs.d.ts +62 -0
  17. package/dist/a2a/memory-runs.d.ts.map +1 -0
  18. package/dist/a2a/memory-runs.js +349 -0
  19. package/dist/a2a/memory-runs.js.map +1 -0
  20. package/dist/a2a/policy.d.ts +15 -0
  21. package/dist/a2a/policy.d.ts.map +1 -0
  22. package/dist/a2a/policy.js +114 -0
  23. package/dist/a2a/policy.js.map +1 -0
  24. package/dist/a2a/push.d.ts +34 -0
  25. package/dist/a2a/push.d.ts.map +1 -0
  26. package/dist/a2a/push.js +180 -0
  27. package/dist/a2a/push.js.map +1 -0
  28. package/dist/a2a/remote.d.ts +155 -0
  29. package/dist/a2a/remote.d.ts.map +1 -0
  30. package/dist/a2a/remote.js +1196 -0
  31. package/dist/a2a/remote.js.map +1 -0
  32. package/dist/a2a/server.d.ts +110 -0
  33. package/dist/a2a/server.d.ts.map +1 -0
  34. package/dist/a2a/server.js +1139 -0
  35. package/dist/a2a/server.js.map +1 -0
  36. package/dist/a2a/signing.d.ts +21 -0
  37. package/dist/a2a/signing.d.ts.map +1 -0
  38. package/dist/a2a/signing.js +305 -0
  39. package/dist/a2a/signing.js.map +1 -0
  40. package/dist/a2a/tasks.d.ts +88 -0
  41. package/dist/a2a/tasks.d.ts.map +1 -0
  42. package/dist/a2a/tasks.js +170 -0
  43. package/dist/a2a/tasks.js.map +1 -0
  44. package/dist/a2a/wire.d.ts +267 -0
  45. package/dist/a2a/wire.d.ts.map +1 -0
  46. package/dist/a2a/wire.js +1202 -0
  47. package/dist/a2a/wire.js.map +1 -0
  48. package/dist/background-types.d.ts +76 -0
  49. package/dist/background-types.d.ts.map +1 -0
  50. package/dist/background-types.js +2 -0
  51. package/dist/background-types.js.map +1 -0
  52. package/dist/child.d.ts +25 -0
  53. package/dist/child.d.ts.map +1 -0
  54. package/dist/child.js +129 -0
  55. package/dist/child.js.map +1 -0
  56. package/dist/code-driver.d.ts +40 -0
  57. package/dist/code-driver.d.ts.map +1 -0
  58. package/dist/code-driver.js +2 -0
  59. package/dist/code-driver.js.map +1 -0
  60. package/dist/code-mode.d.ts +3 -0
  61. package/dist/code-mode.d.ts.map +1 -0
  62. package/dist/code-mode.js +2 -0
  63. package/dist/code-mode.js.map +1 -0
  64. package/dist/code-script.d.ts +3 -0
  65. package/dist/code-script.d.ts.map +1 -0
  66. package/dist/code-script.js +149 -0
  67. package/dist/code-script.js.map +1 -0
  68. package/dist/code.d.ts +75 -0
  69. package/dist/code.d.ts.map +1 -0
  70. package/dist/code.js +326 -0
  71. package/dist/code.js.map +1 -0
  72. package/dist/compaction.d.ts +15 -0
  73. package/dist/compaction.d.ts.map +1 -0
  74. package/dist/compaction.js +168 -0
  75. package/dist/compaction.js.map +1 -0
  76. package/dist/delegation.d.ts +85 -16
  77. package/dist/delegation.d.ts.map +1 -1
  78. package/dist/delegation.js +240 -106
  79. package/dist/delegation.js.map +1 -1
  80. package/dist/evals/driver.d.ts +10 -0
  81. package/dist/evals/driver.d.ts.map +1 -0
  82. package/dist/evals/driver.js +192 -0
  83. package/dist/evals/driver.js.map +1 -0
  84. package/dist/evals/journal.d.ts +26 -0
  85. package/dist/evals/journal.d.ts.map +1 -0
  86. package/dist/evals/journal.js +483 -0
  87. package/dist/evals/journal.js.map +1 -0
  88. package/dist/evals/judge.d.ts +31 -0
  89. package/dist/evals/judge.d.ts.map +1 -0
  90. package/dist/evals/judge.js +142 -0
  91. package/dist/evals/judge.js.map +1 -0
  92. package/dist/evals/report.d.ts +38 -0
  93. package/dist/evals/report.d.ts.map +1 -0
  94. package/dist/evals/report.js +241 -0
  95. package/dist/evals/report.js.map +1 -0
  96. package/dist/evals/runner.d.ts +24 -0
  97. package/dist/evals/runner.d.ts.map +1 -0
  98. package/dist/evals/runner.js +655 -0
  99. package/dist/evals/runner.js.map +1 -0
  100. package/dist/evals/scorers.d.ts +36 -0
  101. package/dist/evals/scorers.d.ts.map +1 -0
  102. package/dist/evals/scorers.js +259 -0
  103. package/dist/evals/scorers.js.map +1 -0
  104. package/dist/evals/simulation.d.ts +7 -0
  105. package/dist/evals/simulation.d.ts.map +1 -0
  106. package/dist/evals/simulation.js +38 -0
  107. package/dist/evals/simulation.js.map +1 -0
  108. package/dist/evals/testing.d.ts +36 -0
  109. package/dist/evals/testing.d.ts.map +1 -0
  110. package/dist/evals/testing.js +87 -0
  111. package/dist/evals/testing.js.map +1 -0
  112. package/dist/evals/trajectory.d.ts +11 -0
  113. package/dist/evals/trajectory.d.ts.map +1 -0
  114. package/dist/evals/trajectory.js +180 -0
  115. package/dist/evals/trajectory.js.map +1 -0
  116. package/dist/evals/types.d.ts +431 -0
  117. package/dist/evals/types.d.ts.map +1 -0
  118. package/dist/evals/types.js +4 -0
  119. package/dist/evals/types.js.map +1 -0
  120. package/dist/evals.d.ts +14 -0
  121. package/dist/evals.d.ts.map +1 -0
  122. package/dist/evals.js +9 -0
  123. package/dist/evals.js.map +1 -0
  124. package/dist/extensions.d.ts +33 -0
  125. package/dist/extensions.d.ts.map +1 -0
  126. package/dist/extensions.js +188 -0
  127. package/dist/extensions.js.map +1 -0
  128. package/dist/handoff.d.ts +58 -0
  129. package/dist/handoff.d.ts.map +1 -0
  130. package/dist/handoff.js +160 -0
  131. package/dist/handoff.js.map +1 -0
  132. package/dist/index.d.ts +14 -0
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js +8 -0
  135. package/dist/index.js.map +1 -1
  136. package/dist/input.d.ts +42 -0
  137. package/dist/input.d.ts.map +1 -0
  138. package/dist/input.js +266 -0
  139. package/dist/input.js.map +1 -0
  140. package/dist/mcp.d.ts +77 -0
  141. package/dist/mcp.d.ts.map +1 -0
  142. package/dist/mcp.js +505 -0
  143. package/dist/mcp.js.map +1 -0
  144. package/dist/memory-store.d.ts +11 -0
  145. package/dist/memory-store.d.ts.map +1 -0
  146. package/dist/memory-store.js +272 -0
  147. package/dist/memory-store.js.map +1 -0
  148. package/dist/memory.d.ts +212 -0
  149. package/dist/memory.d.ts.map +1 -0
  150. package/dist/memory.js +613 -0
  151. package/dist/memory.js.map +1 -0
  152. package/dist/otel.d.ts +74 -0
  153. package/dist/otel.d.ts.map +1 -0
  154. package/dist/otel.js +427 -0
  155. package/dist/otel.js.map +1 -0
  156. package/dist/progress.d.ts +17 -0
  157. package/dist/progress.d.ts.map +1 -0
  158. package/dist/progress.js +193 -0
  159. package/dist/progress.js.map +1 -0
  160. package/dist/quickjs.d.ts +19 -0
  161. package/dist/quickjs.d.ts.map +1 -0
  162. package/dist/quickjs.js +519 -0
  163. package/dist/quickjs.js.map +1 -0
  164. package/dist/recovery.d.ts +10 -0
  165. package/dist/recovery.d.ts.map +1 -0
  166. package/dist/recovery.js +62 -0
  167. package/dist/recovery.js.map +1 -0
  168. package/dist/request.d.ts +88 -0
  169. package/dist/request.d.ts.map +1 -0
  170. package/dist/request.js +422 -0
  171. package/dist/request.js.map +1 -0
  172. package/dist/run.d.ts +16 -4
  173. package/dist/run.d.ts.map +1 -1
  174. package/dist/run.js +2016 -245
  175. package/dist/run.js.map +1 -1
  176. package/dist/runs.d.ts +77 -34
  177. package/dist/runs.d.ts.map +1 -1
  178. package/dist/runs.js +267 -85
  179. package/dist/runs.js.map +1 -1
  180. package/dist/schema-to-ts.d.ts +4 -0
  181. package/dist/schema-to-ts.d.ts.map +1 -0
  182. package/dist/schema-to-ts.js +191 -0
  183. package/dist/schema-to-ts.js.map +1 -0
  184. package/dist/session.d.ts +23 -0
  185. package/dist/session.d.ts.map +1 -0
  186. package/dist/session.js +137 -0
  187. package/dist/session.js.map +1 -0
  188. package/dist/snapshot.d.ts +57 -8
  189. package/dist/snapshot.d.ts.map +1 -1
  190. package/dist/snapshot.js +1206 -109
  191. package/dist/snapshot.js.map +1 -1
  192. package/dist/steering.d.ts +75 -0
  193. package/dist/steering.d.ts.map +1 -0
  194. package/dist/steering.js +214 -0
  195. package/dist/steering.js.map +1 -0
  196. package/dist/subagents.d.ts +141 -0
  197. package/dist/subagents.d.ts.map +1 -0
  198. package/dist/subagents.js +746 -0
  199. package/dist/subagents.js.map +1 -0
  200. package/dist/tool-retry.d.ts +12 -0
  201. package/dist/tool-retry.d.ts.map +1 -0
  202. package/dist/tool-retry.js +53 -0
  203. package/dist/tool-retry.js.map +1 -0
  204. package/dist/tree.d.ts +62 -6
  205. package/dist/tree.d.ts.map +1 -1
  206. package/dist/tree.js +192 -23
  207. package/dist/tree.js.map +1 -1
  208. package/dist/types.d.ts +767 -52
  209. package/dist/types.d.ts.map +1 -1
  210. package/dist/workflow-snapshot.d.ts +8 -0
  211. package/dist/workflow-snapshot.d.ts.map +1 -0
  212. package/dist/workflow-snapshot.js +276 -0
  213. package/dist/workflow-snapshot.js.map +1 -0
  214. package/dist/workflow-types.d.ts +171 -0
  215. package/dist/workflow-types.d.ts.map +1 -0
  216. package/dist/workflow-types.js +2 -0
  217. package/dist/workflow-types.js.map +1 -0
  218. package/dist/workflow.d.ts +19 -0
  219. package/dist/workflow.d.ts.map +1 -0
  220. package/dist/workflow.js +1053 -0
  221. package/dist/workflow.js.map +1 -0
  222. package/examples/a2a-remote.ts +85 -0
  223. package/examples/a2a-server.ts +100 -0
  224. package/examples/background.ts +18 -4
  225. package/examples/code-mode.ts +76 -0
  226. package/examples/conversation.ts +57 -0
  227. package/examples/evals.ts +79 -0
  228. package/examples/guardrails.ts +56 -0
  229. package/examples/handoff.ts +79 -0
  230. package/examples/memory.ts +44 -0
  231. package/examples/otel.ts +99 -0
  232. package/examples/steering.ts +69 -0
  233. package/examples/structured-handoff.ts +92 -0
  234. package/examples/subagents.ts +127 -0
  235. package/examples/workflow.ts +74 -0
  236. package/package.json +58 -6
  237. package/src/a2a/auth.ts +62 -0
  238. package/src/a2a/client.ts +733 -0
  239. package/src/a2a/index.ts +74 -0
  240. package/src/a2a/memory-runs.ts +448 -0
  241. package/src/a2a/policy.ts +148 -0
  242. package/src/a2a/push.ts +251 -0
  243. package/src/a2a/remote.ts +1652 -0
  244. package/src/a2a/server.ts +1390 -0
  245. package/src/a2a/signing.ts +348 -0
  246. package/src/a2a/tasks.ts +260 -0
  247. package/src/a2a/wire.ts +1443 -0
  248. package/src/background-types.ts +86 -0
  249. package/src/child.ts +181 -0
  250. package/src/code-driver.ts +48 -0
  251. package/src/code-mode.ts +12 -0
  252. package/src/code-script.ts +149 -0
  253. package/src/code.ts +424 -0
  254. package/src/compaction.ts +212 -0
  255. package/src/delegation.ts +444 -155
  256. package/src/evals/driver.ts +222 -0
  257. package/src/evals/journal.ts +605 -0
  258. package/src/evals/judge.ts +188 -0
  259. package/src/evals/report.ts +295 -0
  260. package/src/evals/runner.ts +826 -0
  261. package/src/evals/scorers.ts +339 -0
  262. package/src/evals/simulation.ts +46 -0
  263. package/src/evals/testing.ts +126 -0
  264. package/src/evals/trajectory.ts +223 -0
  265. package/src/evals/types.ts +463 -0
  266. package/src/evals.ts +72 -0
  267. package/src/extensions.ts +247 -0
  268. package/src/handoff.ts +214 -0
  269. package/src/index.ts +51 -0
  270. package/src/input.ts +319 -0
  271. package/src/mcp.ts +690 -0
  272. package/src/memory-store.ts +366 -0
  273. package/src/memory.ts +893 -0
  274. package/src/otel.ts +568 -0
  275. package/src/progress.ts +214 -0
  276. package/src/quickjs.ts +524 -0
  277. package/src/recovery.ts +90 -0
  278. package/src/request.ts +513 -0
  279. package/src/run.ts +2678 -313
  280. package/src/runs.ts +464 -133
  281. package/src/schema-to-ts.ts +194 -0
  282. package/src/session.ts +178 -0
  283. package/src/snapshot.ts +1595 -124
  284. package/src/steering.ts +329 -0
  285. package/src/subagents.ts +1084 -0
  286. package/src/tool-retry.ts +86 -0
  287. package/src/tree.ts +223 -27
  288. package/src/types.ts +711 -52
  289. package/src/workflow-snapshot.ts +366 -0
  290. package/src/workflow-types.ts +213 -0
  291. package/src/workflow.ts +1316 -0
@@ -0,0 +1,733 @@
1
+ // EOF handling follows google-adk-python's A2A remote agent, Apache-2.0, Google LLC.
2
+ // REST paths/legacy protobuf JSON checked against a2aproject/A2A release schemas
3
+ // and a2aproject/a2a-js src/compat/v0_3/client/transports/rest_transport.ts.
4
+ import { parseSseStream, type FetchLike } from "@providerkit/core";
5
+ import {
6
+ a2aCardUrl,
7
+ checkA2ACardEndpoints,
8
+ checkA2AEndpoint,
9
+ type A2AEndpointPolicy,
10
+ } from "./policy.ts";
11
+ import {
12
+ A2AError,
13
+ a2aIsMutation,
14
+ a2aLimits,
15
+ a2aMethodName,
16
+ createA2AStreamTracker,
17
+ decodeA2AAgentCard,
18
+ decodeA2AHttpError,
19
+ decodeA2ARequest,
20
+ decodeA2AResult,
21
+ decodeA2ARpcResponse,
22
+ encodeA2ARequest,
23
+ parseA2AJson,
24
+ type A2AAgentCard,
25
+ type A2ADialect,
26
+ type A2AEvent,
27
+ type A2AJson,
28
+ type A2ALimits,
29
+ type A2AMethod,
30
+ type A2AObject,
31
+ type A2AOutcome,
32
+ type A2ARequest,
33
+ type A2ARequests,
34
+ type A2AResults,
35
+ type A2ARpcId,
36
+ type A2AVersion,
37
+ } from "./wire.ts";
38
+
39
+ /** Cancels/releases the local body even when a host fetch does not connect its signal to the reader. */
40
+ function observedBody(
41
+ body: ReadableStream<Uint8Array>,
42
+ signal?: AbortSignal,
43
+ ): ReadableStream<Uint8Array> {
44
+ const reader = body.getReader();
45
+ let ended = false;
46
+ let output: ReadableStreamDefaultController<Uint8Array>;
47
+ const finish = (cancel: boolean) => {
48
+ if (ended) return;
49
+ ended = true;
50
+ signal?.removeEventListener("abort", abort);
51
+ if (cancel) void reader.cancel().catch(() => {});
52
+ reader.releaseLock();
53
+ };
54
+ const abort = () => {
55
+ output.error(signal?.reason);
56
+ finish(true);
57
+ };
58
+ return new ReadableStream<Uint8Array>(
59
+ {
60
+ start(controller) {
61
+ output = controller;
62
+ signal?.addEventListener("abort", abort, { once: true });
63
+ if (signal?.aborted) abort();
64
+ },
65
+ async pull(controller) {
66
+ try {
67
+ const read = await reader.read();
68
+ if (ended) return;
69
+ if (read.done) {
70
+ finish(false);
71
+ controller.close();
72
+ } else controller.enqueue(read.value);
73
+ } catch (error) {
74
+ if (!ended) {
75
+ finish(true);
76
+ controller.error(error);
77
+ }
78
+ }
79
+ },
80
+ cancel() {
81
+ finish(true);
82
+ },
83
+ },
84
+ { highWaterMark: 0 },
85
+ );
86
+ }
87
+
88
+ function jsonType(source: Request | Response): void {
89
+ const type = source.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
90
+ if (type !== "application/json" && type !== "application/a2a+json") {
91
+ void source.body?.cancel().catch(() => {});
92
+ throw new A2AError("protocol", {
93
+ code: -32005,
94
+ status: source instanceof Request ? 415 : source.status,
95
+ });
96
+ }
97
+ }
98
+
99
+ /** Bounded body reader for later server routes too. No form parsing or error-body retention. */
100
+ export async function readA2AJson(
101
+ source: Request | Response,
102
+ options: { signal?: AbortSignal; limits?: Partial<A2ALimits> } = {},
103
+ ): Promise<A2AJson> {
104
+ const l = a2aLimits(options.limits);
105
+ const signal = options.signal ?? (source instanceof Request ? source.signal : undefined);
106
+ if (signal?.aborted) {
107
+ void source.body?.cancel().catch(() => {});
108
+ signal.throwIfAborted();
109
+ }
110
+ jsonType(source);
111
+ const length = source.headers.get("content-length");
112
+ if (length && /^\d+$/.test(length) && Number(length) > l.bodyBytes) {
113
+ void source.body?.cancel().catch(() => {});
114
+ throw new A2AError("limit", { status: source instanceof Request ? 413 : source.status });
115
+ }
116
+ if (!source.body) throw new A2AError("invalid");
117
+ const reader = observedBody(source.body, signal).getReader();
118
+ const decoder = new TextDecoder("utf-8", { fatal: true });
119
+ let bytes = 0;
120
+ let text = "";
121
+ let drained = false;
122
+ try {
123
+ for (;;) {
124
+ signal?.throwIfAborted();
125
+ let read: ReadableStreamReadResult<Uint8Array>;
126
+ try {
127
+ read = await reader.read();
128
+ } catch {
129
+ signal?.throwIfAborted();
130
+ throw new A2AError("network");
131
+ }
132
+ signal?.throwIfAborted();
133
+ if (read.done) {
134
+ drained = true;
135
+ break;
136
+ }
137
+ bytes += read.value.byteLength;
138
+ if (bytes > l.bodyBytes)
139
+ throw new A2AError("limit", { status: source instanceof Request ? 413 : source.status });
140
+ text += decoder.decode(read.value, { stream: true });
141
+ }
142
+ return parseA2AJson(text + decoder.decode(), l);
143
+ } catch (error) {
144
+ signal?.throwIfAborted();
145
+ throw error instanceof A2AError ? error : new A2AError("invalid");
146
+ } finally {
147
+ if (!drained) void reader.cancel().catch(() => {});
148
+ reader.releaseLock();
149
+ }
150
+ }
151
+
152
+ interface RequestHooks {
153
+ fetch?: FetchLike;
154
+ /** Host-only hook for credentials, trace headers and request IDs. Never populated from messages. */
155
+ headers?: (request: { url: string; method: string }) => HeadersInit | Promise<HeadersInit>;
156
+ /** Read once per request. A rejected token never causes a mutation to be sent again. */
157
+ token?: { getToken(): Promise<{ accessToken: string }> };
158
+ }
159
+ export interface A2AClientOptions extends A2ADialect, RequestHooks {
160
+ endpoint: string;
161
+ tenant?: string;
162
+ cardUrl?: string;
163
+ policy: A2AEndpointPolicy;
164
+ extensions?: readonly string[];
165
+ limits?: Partial<A2ALimits>;
166
+ maxResultBytes?: number;
167
+ /** Preparation, headers and unary-body deadline. Streaming bodies have their own idle deadline. */
168
+ timeoutMs?: number;
169
+ idleMs?: number;
170
+ }
171
+ export interface A2ACallOptions {
172
+ signal?: AbortSignal;
173
+ requestId?: A2ARpcId;
174
+ }
175
+ export interface A2AObservation extends AsyncIterableIterator<A2AEvent> {
176
+ close(): Promise<void>;
177
+ }
178
+ type StreamingMethod = "SendStreamingMessage" | "SubscribeToTask";
179
+ type UnaryMethod = Exclude<A2AMethod, StreamingMethod>;
180
+ export interface A2AClient {
181
+ call<M extends UnaryMethod>(
182
+ method: M,
183
+ params: A2ARequests[M],
184
+ options?: A2ACallOptions,
185
+ ): Promise<A2AResults[M]>;
186
+ observe<M extends StreamingMethod>(
187
+ method: M,
188
+ params: A2ARequests[M],
189
+ options?: A2ACallOptions,
190
+ ): A2AObservation;
191
+ }
192
+
193
+ function positive(value: number): number {
194
+ if (!Number.isSafeInteger(value) || value < 1) throw new A2AError("invalid");
195
+ return value;
196
+ }
197
+ function segment(value: string | undefined): string {
198
+ if (!value || value === "." || value === "..") throw new A2AError("invalid");
199
+ return encodeURIComponent(value);
200
+ }
201
+
202
+ /** Base URL is the advertised binding endpoint; 0.3 adds /v1, as its REST schema requires. */
203
+ export function encodeA2AHttpRequest(
204
+ endpoint: string,
205
+ request: A2ARequest,
206
+ version: A2AVersion,
207
+ overrides?: Partial<A2ALimits>,
208
+ ): { url: string; method: string; body?: A2AObject } {
209
+ const d = { version, binding: "HTTP+JSON" } as const;
210
+ const wire = encodeA2ARequest(request, d, overrides).params;
211
+ const url = new URL(endpoint);
212
+ const root = `${url.pathname.replace(/\/+$/, "")}${version === "0.3" ? "/v1" : request.params.tenant ? `/${segment(request.params.tenant)}` : ""}`;
213
+ let path: string;
214
+ let method = "GET";
215
+ let body: A2AObject | undefined;
216
+ switch (request.method) {
217
+ case "SendMessage":
218
+ case "SendStreamingMessage":
219
+ path = `/message:${request.method === "SendMessage" ? "send" : "stream"}`;
220
+ method = "POST";
221
+ body = wire;
222
+ break;
223
+ case "GetTask":
224
+ case "CancelTask":
225
+ case "SubscribeToTask": {
226
+ path = `/tasks/${segment(request.params.id)}${request.method === "GetTask" ? "" : request.method === "CancelTask" ? ":cancel" : ":subscribe"}`;
227
+ if (request.method === "CancelTask") {
228
+ method = "POST";
229
+ body = wire;
230
+ } else if (request.params.historyLength !== undefined)
231
+ url.searchParams.set("historyLength", String(request.params.historyLength));
232
+ break;
233
+ }
234
+ case "ListTasks":
235
+ path = "/tasks";
236
+ for (const [key, value] of Object.entries(wire))
237
+ if (key !== "tenant") url.searchParams.set(key, String(value));
238
+ break;
239
+ case "CreateTaskPushNotificationConfig":
240
+ path = `/tasks/${segment(request.params.taskId)}/pushNotificationConfigs`;
241
+ method = "POST";
242
+ body = wire;
243
+ break;
244
+ case "GetTaskPushNotificationConfig":
245
+ case "DeleteTaskPushNotificationConfig":
246
+ case "ListTaskPushNotificationConfigs": {
247
+ path = `/tasks/${segment(request.params.taskId)}/pushNotificationConfigs${request.method === "ListTaskPushNotificationConfigs" ? "" : `/${segment(request.params.id)}`}`;
248
+ if (request.method === "DeleteTaskPushNotificationConfig") method = "DELETE";
249
+ if (request.params.pageSize !== undefined)
250
+ url.searchParams.set("pageSize", String(request.params.pageSize));
251
+ if (request.params.pageToken !== undefined)
252
+ url.searchParams.set("pageToken", request.params.pageToken);
253
+ break;
254
+ }
255
+ case "GetExtendedAgentCard":
256
+ path = version === "1.0" ? "/extendedAgentCard" : "/card";
257
+ break;
258
+ }
259
+ url.pathname = root + path;
260
+ return { url: url.href, method, body };
261
+ }
262
+
263
+ /** Authenticate first. This only decodes a Request and never starts, stores or cancels a task. */
264
+ export async function decodeA2AHttpRequest(
265
+ request: Request,
266
+ options: { baseUrl: string; version: A2AVersion; tenant?: string; limits?: Partial<A2ALimits> },
267
+ ): Promise<A2ARequest> {
268
+ const { version } = options;
269
+ const url = new URL(request.url);
270
+ const prefix = `${new URL(options.baseUrl).pathname.replace(/\/+$/, "")}${version === "0.3" ? "/v1" : options.tenant ? `/${segment(options.tenant)}` : ""}`;
271
+ if (!url.pathname.startsWith(`${prefix}/`)) throw new A2AError("protocol", { code: -32601 });
272
+ const path = url.pathname.slice(prefix.length);
273
+ let method: A2AMethod;
274
+ let taskId: string | undefined;
275
+ let configId: string | undefined;
276
+ let verb = "GET";
277
+ if (path === "/message:send" || path === "/message:stream") {
278
+ method = path.endsWith(":send") ? "SendMessage" : "SendStreamingMessage";
279
+ verb = "POST";
280
+ } else if (path === "/tasks") method = "ListTasks";
281
+ else if (path === (version === "1.0" ? "/extendedAgentCard" : "/card"))
282
+ method = "GetExtendedAgentCard";
283
+ else {
284
+ const match =
285
+ /^\/tasks\/([^/:]+)(?:(:cancel|:subscribe)|\/pushNotificationConfigs(?:\/([^/]+))?)?$/.exec(
286
+ path,
287
+ );
288
+ if (!match) throw new A2AError("protocol", { code: -32601 });
289
+ try {
290
+ taskId = decodeURIComponent(match[1]!);
291
+ configId = match[3] && decodeURIComponent(match[3]);
292
+ } catch {
293
+ throw new A2AError("invalid");
294
+ }
295
+ if (match[2]) {
296
+ method = match[2] === ":cancel" ? "CancelTask" : "SubscribeToTask";
297
+ if (method === "CancelTask") verb = "POST";
298
+ } else if (path.includes("/pushNotificationConfigs")) {
299
+ method = configId
300
+ ? request.method === "DELETE"
301
+ ? "DeleteTaskPushNotificationConfig"
302
+ : "GetTaskPushNotificationConfig"
303
+ : request.method === "POST"
304
+ ? "CreateTaskPushNotificationConfig"
305
+ : "ListTaskPushNotificationConfigs";
306
+ if (method === "DeleteTaskPushNotificationConfig") verb = "DELETE";
307
+ if (method === "CreateTaskPushNotificationConfig") verb = "POST";
308
+ } else method = "GetTask";
309
+ }
310
+ if (request.method !== verb) throw new A2AError("protocol", { code: -32600, status: 405 });
311
+ let params: A2AObject = {};
312
+ if (verb === "POST") {
313
+ if (request.body) {
314
+ const value = await readA2AJson(request, { limits: options.limits });
315
+ if (!value || typeof value !== "object" || Array.isArray(value))
316
+ throw new A2AError("invalid");
317
+ params = value;
318
+ } else if (method !== "CancelTask") throw new A2AError("invalid");
319
+ }
320
+ url.searchParams.forEach((value, key) => {
321
+ if (Object.hasOwn(params, key) || url.searchParams.getAll(key).length !== 1)
322
+ throw new A2AError("invalid");
323
+ if (["historyLength", "pageSize"].includes(key)) {
324
+ if (!/^\d+$/.test(value)) throw new A2AError("invalid");
325
+ params[key] = Number(value);
326
+ } else if (key === "includeArtifacts") {
327
+ if (!["true", "false"].includes(value)) throw new A2AError("invalid");
328
+ params[key] = value === "true";
329
+ } else params[key] = value;
330
+ });
331
+ const put = (key: string, value: string | undefined) => {
332
+ if (value === undefined) return;
333
+ if (Object.hasOwn(params, key) && params[key] !== value) throw new A2AError("invalid");
334
+ params[key] = value;
335
+ };
336
+ put("tenant", options.tenant);
337
+ if (version === "0.3" && taskId) {
338
+ const resource = `tasks/${segment(taskId)}`;
339
+ if (method === "CreateTaskPushNotificationConfig") {
340
+ const name = params.name;
341
+ if (typeof name !== "string" || !name.startsWith(`${resource}/pushNotificationConfigs/`))
342
+ throw new A2AError("invalid");
343
+ } else
344
+ put(
345
+ method === "ListTaskPushNotificationConfigs" ? "parent" : "name",
346
+ `${resource}${configId ? `/pushNotificationConfigs/${segment(configId)}` : ""}`,
347
+ );
348
+ } else {
349
+ const push = method.includes("PushNotification");
350
+ put(push ? "taskId" : "id", taskId);
351
+ if (push) put("id", configId);
352
+ }
353
+ return decodeA2ARequest(
354
+ a2aMethodName(method, version),
355
+ params,
356
+ { version, binding: "HTTP+JSON" },
357
+ options.limits,
358
+ );
359
+ }
360
+
361
+ /** Host hooks need not honor a signal. Stop waiting and never start the next hook after abort. */
362
+ function untilAbort<T>(
363
+ signal: AbortSignal,
364
+ work: () => T | Promise<T>,
365
+ discard?: (value: T) => void,
366
+ ): Promise<T> {
367
+ return new Promise((resolve, reject) => {
368
+ const abort = () => reject(signal.reason);
369
+ if (signal.aborted) {
370
+ abort();
371
+ return;
372
+ }
373
+ signal.addEventListener("abort", abort, { once: true });
374
+ void Promise.resolve()
375
+ .then(() => {
376
+ signal.throwIfAborted();
377
+ return work();
378
+ })
379
+ .then(
380
+ (value) => {
381
+ signal.removeEventListener("abort", abort);
382
+ if (signal.aborted) {
383
+ discard?.(value);
384
+ reject(signal.reason);
385
+ } else resolve(value);
386
+ },
387
+ (error: unknown) => {
388
+ signal.removeEventListener("abort", abort);
389
+ reject(signal.aborted ? signal.reason : error);
390
+ },
391
+ );
392
+ });
393
+ }
394
+
395
+ async function sendOnce(
396
+ url: string,
397
+ init: RequestInit,
398
+ hooks: RequestHooks,
399
+ signal: AbortSignal,
400
+ onSend?: () => void,
401
+ ): Promise<Response> {
402
+ const headers = new Headers(
403
+ await untilAbort(signal, () => hooks.headers?.({ url, method: init.method ?? "GET" })),
404
+ );
405
+ const source = hooks.token;
406
+ if (source) {
407
+ const token = (await untilAbort(signal, () => source.getToken())).accessToken;
408
+ if (!/^[A-Za-z0-9\-._~+/]+=*$/.test(token)) throw new A2AError("invalid");
409
+ headers.set("authorization", `Bearer ${token}`);
410
+ }
411
+ new Headers(init.headers).forEach((value, key) => headers.set(key, value));
412
+ const response = await untilAbort(
413
+ signal,
414
+ () => {
415
+ onSend?.();
416
+ return (hooks.fetch ?? globalThis.fetch)(url, {
417
+ ...init,
418
+ headers,
419
+ signal,
420
+ redirect: "error",
421
+ credentials: "omit",
422
+ });
423
+ },
424
+ (late) => {
425
+ void late.body?.cancel().catch(() => {});
426
+ },
427
+ );
428
+ if (
429
+ response.redirected ||
430
+ response.type === "opaqueredirect" ||
431
+ response.status === 0 ||
432
+ (response.status >= 300 && response.status < 400)
433
+ ) {
434
+ void response.body?.cancel().catch(() => {});
435
+ throw new A2AError("endpoint", { status: response.status });
436
+ }
437
+ return response;
438
+ }
439
+ function remap(error: unknown, outcome: A2AOutcome, signal?: AbortSignal, timedOut = false): never {
440
+ signal?.throwIfAborted();
441
+ if (timedOut) throw new A2AError("timeout", { outcome });
442
+ throw error instanceof A2AError
443
+ ? new A2AError(error.kind, { code: error.code, status: error.status, outcome })
444
+ : new A2AError("network", { outcome });
445
+ }
446
+ async function responseError(
447
+ response: Response,
448
+ signal: AbortSignal,
449
+ limits: A2ALimits,
450
+ ): Promise<never> {
451
+ try {
452
+ const value = await readA2AJson(response, { signal, limits });
453
+ throw decodeA2AHttpError(value, response.status, limits);
454
+ } catch (error) {
455
+ signal.throwIfAborted();
456
+ if (
457
+ error instanceof A2AError &&
458
+ error.kind === "protocol" &&
459
+ error.code !== -32700 &&
460
+ error.code !== -32005
461
+ )
462
+ throw error;
463
+ throw new A2AError("http", { status: response.status });
464
+ }
465
+ }
466
+
467
+ export async function fetchA2AAgentCard(
468
+ source: string,
469
+ options: RequestHooks & {
470
+ version: A2AVersion;
471
+ policy: A2AEndpointPolicy;
472
+ signal?: AbortSignal;
473
+ timeoutMs?: number;
474
+ limits?: Partial<A2ALimits>;
475
+ verifyCard?: (
476
+ card: A2AAgentCard,
477
+ context: { url: string; fetchedAt: number },
478
+ ) => void | Promise<void>;
479
+ },
480
+ ): Promise<A2AAgentCard> {
481
+ const controller = new AbortController();
482
+ const signal = options.signal
483
+ ? AbortSignal.any([options.signal, controller.signal])
484
+ : controller.signal;
485
+ const timer = setTimeout(() => controller.abort(), positive(options.timeoutMs ?? 10_000));
486
+ try {
487
+ signal.throwIfAborted();
488
+ const url = await untilAbort(signal, () =>
489
+ checkA2AEndpoint(a2aCardUrl(source), "card", options.policy),
490
+ );
491
+ const response = await sendOnce(
492
+ url.href,
493
+ { method: "GET", headers: { accept: "application/json", "A2A-Version": options.version } },
494
+ options,
495
+ signal,
496
+ );
497
+ const limits = a2aLimits({ bodyBytes: 1024 * 1024, ...options.limits });
498
+ if (!response.ok) return await responseError(response, signal, limits);
499
+ const card = decodeA2AAgentCard(
500
+ await readA2AJson(response, { signal, limits }),
501
+ options.version,
502
+ limits,
503
+ );
504
+ await untilAbort(signal, () =>
505
+ options.verifyCard?.(card, { url: url.href, fetchedAt: Date.now() }),
506
+ );
507
+ await untilAbort(signal, () => checkA2ACardEndpoints(card, url.href, options.policy));
508
+ signal.throwIfAborted();
509
+ return card;
510
+ } catch (error) {
511
+ return remap(error, "read", options.signal, controller.signal.aborted);
512
+ } finally {
513
+ clearTimeout(timer);
514
+ }
515
+ }
516
+
517
+ export function createA2AClient(options: A2AClientOptions): A2AClient {
518
+ if (
519
+ !["1.0", "0.3"].includes(options.version) ||
520
+ !["JSONRPC", "HTTP+JSON"].includes(options.binding)
521
+ )
522
+ throw new A2AError("protocol", { code: -32009 });
523
+ const d: A2ADialect = { version: options.version, binding: options.binding };
524
+ const limits = a2aLimits(options.limits);
525
+ const timeoutMs = positive(options.timeoutMs ?? 60_000);
526
+ const idleMs = positive(options.idleMs ?? 120_000);
527
+ const maxResultBytes = positive(options.maxResultBytes ?? 1024 * 1024);
528
+ const prepare = async (
529
+ request: A2ARequest,
530
+ requestId: A2ARpcId,
531
+ streaming: boolean,
532
+ signal: AbortSignal,
533
+ ) => {
534
+ if (options.tenant && request.params.tenant && options.tenant !== request.params.tenant)
535
+ throw new A2AError("invalid");
536
+ request = {
537
+ ...request,
538
+ params: { ...request.params, tenant: options.tenant ?? request.params.tenant },
539
+ } as A2ARequest;
540
+ await untilAbort(signal, () =>
541
+ checkA2AEndpoint(options.endpoint, "rpc", options.policy, options.cardUrl),
542
+ );
543
+ const spec =
544
+ d.binding === "JSONRPC"
545
+ ? {
546
+ url: options.endpoint,
547
+ method: "POST",
548
+ body: { jsonrpc: "2.0", id: requestId, ...encodeA2ARequest(request, d, limits) },
549
+ }
550
+ : encodeA2AHttpRequest(options.endpoint, request, d.version, limits);
551
+ await untilAbort(signal, () =>
552
+ checkA2AEndpoint(spec.url, "rpc", options.policy, options.cardUrl),
553
+ );
554
+ const headers = new Headers({
555
+ accept: streaming ? "text/event-stream" : "application/a2a+json, application/json",
556
+ "A2A-Version": d.version,
557
+ });
558
+ if (spec.body)
559
+ headers.set(
560
+ "content-type",
561
+ d.version === "1.0" ? "application/a2a+json" : "application/json",
562
+ );
563
+ if (options.extensions?.length) headers.set("A2A-Extensions", options.extensions.join(","));
564
+ const body = spec.body === undefined ? undefined : JSON.stringify(spec.body);
565
+ if (body !== undefined) parseA2AJson(body, limits);
566
+ return { url: spec.url, init: { method: spec.method, headers, body }, request };
567
+ };
568
+ const expected = (request: A2ARequest): { taskId?: string; contextId?: string } => {
569
+ if (request.method === "SendMessage" || request.method === "SendStreamingMessage")
570
+ return { taskId: request.params.message.taskId, contextId: request.params.message.contextId };
571
+ if (
572
+ request.method === "GetTask" ||
573
+ request.method === "CancelTask" ||
574
+ request.method === "SubscribeToTask"
575
+ )
576
+ return { taskId: request.params.id };
577
+ return {};
578
+ };
579
+ return {
580
+ async call(method, params, callOptions = {}) {
581
+ const controller = new AbortController();
582
+ const signal = callOptions.signal
583
+ ? AbortSignal.any([controller.signal, callOptions.signal])
584
+ : controller.signal;
585
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
586
+ let outcome: A2AOutcome = "not-sent";
587
+ try {
588
+ signal.throwIfAborted();
589
+ const requestId = callOptions.requestId ?? crypto.randomUUID();
590
+ // The generic method and params are correlated at the public call boundary.
591
+ const request = { method, params } as A2ARequest;
592
+ const spec = await prepare(request, requestId, false, signal);
593
+ signal.throwIfAborted();
594
+ const response = await sendOnce(spec.url, spec.init, options, signal, () => {
595
+ outcome = a2aIsMutation(method) ? "unknown" : "read";
596
+ });
597
+ if (!response.ok) return await responseError(response, signal, limits);
598
+ const value =
599
+ method === "DeleteTaskPushNotificationConfig" &&
600
+ response.status === 204 &&
601
+ d.binding === "HTTP+JSON"
602
+ ? {}
603
+ : await readA2AJson(response, { signal, limits });
604
+ const payload =
605
+ d.binding === "JSONRPC" ? decodeA2ARpcResponse(value, requestId, limits) : value;
606
+ const result = decodeA2AResult(method, payload, d, limits);
607
+ if (result && "kind" in result)
608
+ createA2AStreamTracker(expected(request), maxResultBytes).accept(result);
609
+ if (result && "taskId" in params && params.taskId) {
610
+ const configs = "url" in result ? [result] : "configs" in result ? result.configs : [];
611
+ for (const config of configs) {
612
+ if (
613
+ !("taskId" in config) ||
614
+ config.taskId !== params.taskId ||
615
+ ("id" in params &&
616
+ params.id !== undefined &&
617
+ (!("id" in config) || config.id !== params.id))
618
+ )
619
+ throw new A2AError("invalid");
620
+ }
621
+ }
622
+ return result;
623
+ } catch (error) {
624
+ return remap(error, outcome, callOptions.signal, controller.signal.aborted);
625
+ } finally {
626
+ clearTimeout(timer);
627
+ }
628
+ },
629
+ observe(method, params, callOptions = {}) {
630
+ const stop = new AbortController();
631
+ const deadline = new AbortController();
632
+ const signal = AbortSignal.any([
633
+ stop.signal,
634
+ deadline.signal,
635
+ ...(callOptions.signal ? [callOptions.signal] : []),
636
+ ]);
637
+ let timer: ReturnType<typeof setTimeout> | undefined;
638
+ let outcome: A2AOutcome = "not-sent";
639
+ const arm = (ms: number) => {
640
+ clearTimeout(timer);
641
+ timer = setTimeout(() => deadline.abort(), ms);
642
+ };
643
+ const iterator = (async function* (): AsyncGenerator<A2AEvent> {
644
+ try {
645
+ signal.throwIfAborted();
646
+ arm(timeoutMs);
647
+ const requestId = callOptions.requestId ?? crypto.randomUUID();
648
+ const request = { method, params } as A2ARequest;
649
+ const spec = await prepare(request, requestId, true, signal);
650
+ signal.throwIfAborted();
651
+ const response = await sendOnce(spec.url, spec.init, options, signal, () => {
652
+ outcome = a2aIsMutation(method) ? "unknown" : "read";
653
+ });
654
+ if (!response.ok) return await responseError(response, signal, limits);
655
+ if (
656
+ !response.body ||
657
+ response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() !==
658
+ "text/event-stream"
659
+ ) {
660
+ if (d.binding === "JSONRPC" && response.body) {
661
+ // A refused streaming method may return an ordinary JSON-RPC error with HTTP200.
662
+ // Decode its bounded envelope first; a non-stream success is still invalid here.
663
+ decodeA2ARpcResponse(
664
+ await readA2AJson(response, { signal, limits }),
665
+ requestId,
666
+ limits,
667
+ );
668
+ }
669
+ void response.body?.cancel().catch(() => {});
670
+ throw new A2AError("invalid");
671
+ }
672
+ arm(idleMs);
673
+ const tracker = createA2AStreamTracker(expected(request), maxResultBytes, {
674
+ method,
675
+ version: d.version,
676
+ });
677
+ const frames = parseSseStream(observedBody(response.body, signal), {
678
+ signal,
679
+ maxFrameChars: limits.bodyBytes,
680
+ onActivity: () => arm(idleMs),
681
+ });
682
+ for await (const frame of frames) {
683
+ signal.throwIfAborted();
684
+ const value = parseA2AJson(frame, limits);
685
+ const payload =
686
+ d.binding === "JSONRPC" ? decodeA2ARpcResponse(value, requestId, limits) : value;
687
+ if (
688
+ d.binding === "HTTP+JSON" &&
689
+ payload &&
690
+ typeof payload === "object" &&
691
+ !Array.isArray(payload) &&
692
+ ("error" in payload ||
693
+ (d.version === "0.3" && typeof payload.code === "number" && payload.code < 0))
694
+ )
695
+ throw decodeA2AHttpError(payload, 200, limits);
696
+ const event = decodeA2AResult(method, payload, d, limits);
697
+ const closed = tracker.accept(event);
698
+ if (closed) await frames.return(undefined);
699
+ yield event;
700
+ if (closed) return;
701
+ }
702
+ signal.throwIfAborted();
703
+ throw new A2AError("stream-cut");
704
+ } catch (error) {
705
+ if (stop.signal.aborted && !callOptions.signal?.aborted) return;
706
+ remap(error, outcome, callOptions.signal, deadline.signal.aborted);
707
+ } finally {
708
+ clearTimeout(timer);
709
+ }
710
+ })();
711
+ return {
712
+ [Symbol.asyncIterator]() {
713
+ return this;
714
+ },
715
+ next() {
716
+ return iterator.next();
717
+ },
718
+ async return() {
719
+ stop.abort();
720
+ return iterator.return(undefined);
721
+ },
722
+ async throw(error: unknown) {
723
+ stop.abort();
724
+ return iterator.throw(error);
725
+ },
726
+ async close() {
727
+ stop.abort();
728
+ await iterator.return(undefined);
729
+ },
730
+ };
731
+ },
732
+ };
733
+ }