@providerkit/agents 0.0.0-stage → 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 (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/README.md +2328 -2
  4. package/THIRD_PARTY_NOTICES.md +521 -0
  5. package/dist/a2a/auth.d.ts +10 -0
  6. package/dist/a2a/auth.d.ts.map +1 -0
  7. package/dist/a2a/auth.js +52 -0
  8. package/dist/a2a/auth.js.map +1 -0
  9. package/dist/a2a/client.d.ts +74 -0
  10. package/dist/a2a/client.d.ts.map +1 -0
  11. package/dist/a2a/client.js +601 -0
  12. package/dist/a2a/client.js.map +1 -0
  13. package/dist/a2a/index.d.ts +22 -0
  14. package/dist/a2a/index.d.ts.map +1 -0
  15. package/dist/a2a/index.js +11 -0
  16. package/dist/a2a/index.js.map +1 -0
  17. package/dist/a2a/memory-runs.d.ts +62 -0
  18. package/dist/a2a/memory-runs.d.ts.map +1 -0
  19. package/dist/a2a/memory-runs.js +349 -0
  20. package/dist/a2a/memory-runs.js.map +1 -0
  21. package/dist/a2a/policy.d.ts +15 -0
  22. package/dist/a2a/policy.d.ts.map +1 -0
  23. package/dist/a2a/policy.js +114 -0
  24. package/dist/a2a/policy.js.map +1 -0
  25. package/dist/a2a/push.d.ts +34 -0
  26. package/dist/a2a/push.d.ts.map +1 -0
  27. package/dist/a2a/push.js +180 -0
  28. package/dist/a2a/push.js.map +1 -0
  29. package/dist/a2a/remote.d.ts +155 -0
  30. package/dist/a2a/remote.d.ts.map +1 -0
  31. package/dist/a2a/remote.js +1196 -0
  32. package/dist/a2a/remote.js.map +1 -0
  33. package/dist/a2a/server.d.ts +110 -0
  34. package/dist/a2a/server.d.ts.map +1 -0
  35. package/dist/a2a/server.js +1139 -0
  36. package/dist/a2a/server.js.map +1 -0
  37. package/dist/a2a/signing.d.ts +21 -0
  38. package/dist/a2a/signing.d.ts.map +1 -0
  39. package/dist/a2a/signing.js +305 -0
  40. package/dist/a2a/signing.js.map +1 -0
  41. package/dist/a2a/tasks.d.ts +88 -0
  42. package/dist/a2a/tasks.d.ts.map +1 -0
  43. package/dist/a2a/tasks.js +170 -0
  44. package/dist/a2a/tasks.js.map +1 -0
  45. package/dist/a2a/wire.d.ts +267 -0
  46. package/dist/a2a/wire.d.ts.map +1 -0
  47. package/dist/a2a/wire.js +1202 -0
  48. package/dist/a2a/wire.js.map +1 -0
  49. package/dist/background-types.d.ts +76 -0
  50. package/dist/background-types.d.ts.map +1 -0
  51. package/dist/background-types.js +2 -0
  52. package/dist/background-types.js.map +1 -0
  53. package/dist/child.d.ts +25 -0
  54. package/dist/child.d.ts.map +1 -0
  55. package/dist/child.js +129 -0
  56. package/dist/child.js.map +1 -0
  57. package/dist/code-driver.d.ts +40 -0
  58. package/dist/code-driver.d.ts.map +1 -0
  59. package/dist/code-driver.js +2 -0
  60. package/dist/code-driver.js.map +1 -0
  61. package/dist/code-mode.d.ts +3 -0
  62. package/dist/code-mode.d.ts.map +1 -0
  63. package/dist/code-mode.js +2 -0
  64. package/dist/code-mode.js.map +1 -0
  65. package/dist/code-script.d.ts +3 -0
  66. package/dist/code-script.d.ts.map +1 -0
  67. package/dist/code-script.js +149 -0
  68. package/dist/code-script.js.map +1 -0
  69. package/dist/code.d.ts +75 -0
  70. package/dist/code.d.ts.map +1 -0
  71. package/dist/code.js +326 -0
  72. package/dist/code.js.map +1 -0
  73. package/dist/compaction.d.ts +15 -0
  74. package/dist/compaction.d.ts.map +1 -0
  75. package/dist/compaction.js +168 -0
  76. package/dist/compaction.js.map +1 -0
  77. package/dist/delegation.d.ts +135 -0
  78. package/dist/delegation.d.ts.map +1 -0
  79. package/dist/delegation.js +401 -0
  80. package/dist/delegation.js.map +1 -0
  81. package/dist/evals/driver.d.ts +10 -0
  82. package/dist/evals/driver.d.ts.map +1 -0
  83. package/dist/evals/driver.js +192 -0
  84. package/dist/evals/driver.js.map +1 -0
  85. package/dist/evals/journal.d.ts +26 -0
  86. package/dist/evals/journal.d.ts.map +1 -0
  87. package/dist/evals/journal.js +483 -0
  88. package/dist/evals/journal.js.map +1 -0
  89. package/dist/evals/judge.d.ts +31 -0
  90. package/dist/evals/judge.d.ts.map +1 -0
  91. package/dist/evals/judge.js +142 -0
  92. package/dist/evals/judge.js.map +1 -0
  93. package/dist/evals/report.d.ts +38 -0
  94. package/dist/evals/report.d.ts.map +1 -0
  95. package/dist/evals/report.js +241 -0
  96. package/dist/evals/report.js.map +1 -0
  97. package/dist/evals/runner.d.ts +24 -0
  98. package/dist/evals/runner.d.ts.map +1 -0
  99. package/dist/evals/runner.js +655 -0
  100. package/dist/evals/runner.js.map +1 -0
  101. package/dist/evals/scorers.d.ts +36 -0
  102. package/dist/evals/scorers.d.ts.map +1 -0
  103. package/dist/evals/scorers.js +259 -0
  104. package/dist/evals/scorers.js.map +1 -0
  105. package/dist/evals/simulation.d.ts +7 -0
  106. package/dist/evals/simulation.d.ts.map +1 -0
  107. package/dist/evals/simulation.js +38 -0
  108. package/dist/evals/simulation.js.map +1 -0
  109. package/dist/evals/testing.d.ts +36 -0
  110. package/dist/evals/testing.d.ts.map +1 -0
  111. package/dist/evals/testing.js +87 -0
  112. package/dist/evals/testing.js.map +1 -0
  113. package/dist/evals/trajectory.d.ts +11 -0
  114. package/dist/evals/trajectory.d.ts.map +1 -0
  115. package/dist/evals/trajectory.js +180 -0
  116. package/dist/evals/trajectory.js.map +1 -0
  117. package/dist/evals/types.d.ts +431 -0
  118. package/dist/evals/types.d.ts.map +1 -0
  119. package/dist/evals/types.js +4 -0
  120. package/dist/evals/types.js.map +1 -0
  121. package/dist/evals.d.ts +14 -0
  122. package/dist/evals.d.ts.map +1 -0
  123. package/dist/evals.js +9 -0
  124. package/dist/evals.js.map +1 -0
  125. package/dist/extensions.d.ts +33 -0
  126. package/dist/extensions.d.ts.map +1 -0
  127. package/dist/extensions.js +188 -0
  128. package/dist/extensions.js.map +1 -0
  129. package/dist/handoff.d.ts +58 -0
  130. package/dist/handoff.d.ts.map +1 -0
  131. package/dist/handoff.js +160 -0
  132. package/dist/handoff.js.map +1 -0
  133. package/dist/index.d.ts +19 -0
  134. package/dist/index.d.ts.map +1 -0
  135. package/dist/index.js +11 -0
  136. package/dist/index.js.map +1 -0
  137. package/dist/input.d.ts +42 -0
  138. package/dist/input.d.ts.map +1 -0
  139. package/dist/input.js +266 -0
  140. package/dist/input.js.map +1 -0
  141. package/dist/mcp.d.ts +77 -0
  142. package/dist/mcp.d.ts.map +1 -0
  143. package/dist/mcp.js +505 -0
  144. package/dist/mcp.js.map +1 -0
  145. package/dist/memory-store.d.ts +11 -0
  146. package/dist/memory-store.d.ts.map +1 -0
  147. package/dist/memory-store.js +272 -0
  148. package/dist/memory-store.js.map +1 -0
  149. package/dist/memory.d.ts +212 -0
  150. package/dist/memory.d.ts.map +1 -0
  151. package/dist/memory.js +613 -0
  152. package/dist/memory.js.map +1 -0
  153. package/dist/otel.d.ts +74 -0
  154. package/dist/otel.d.ts.map +1 -0
  155. package/dist/otel.js +427 -0
  156. package/dist/otel.js.map +1 -0
  157. package/dist/progress.d.ts +17 -0
  158. package/dist/progress.d.ts.map +1 -0
  159. package/dist/progress.js +193 -0
  160. package/dist/progress.js.map +1 -0
  161. package/dist/quickjs.d.ts +19 -0
  162. package/dist/quickjs.d.ts.map +1 -0
  163. package/dist/quickjs.js +519 -0
  164. package/dist/quickjs.js.map +1 -0
  165. package/dist/recovery.d.ts +10 -0
  166. package/dist/recovery.d.ts.map +1 -0
  167. package/dist/recovery.js +62 -0
  168. package/dist/recovery.js.map +1 -0
  169. package/dist/request.d.ts +88 -0
  170. package/dist/request.d.ts.map +1 -0
  171. package/dist/request.js +422 -0
  172. package/dist/request.js.map +1 -0
  173. package/dist/run.d.ts +20 -0
  174. package/dist/run.d.ts.map +1 -0
  175. package/dist/run.js +2407 -0
  176. package/dist/run.js.map +1 -0
  177. package/dist/runs.d.ts +110 -0
  178. package/dist/runs.d.ts.map +1 -0
  179. package/dist/runs.js +438 -0
  180. package/dist/runs.js.map +1 -0
  181. package/dist/schema-to-ts.d.ts +4 -0
  182. package/dist/schema-to-ts.d.ts.map +1 -0
  183. package/dist/schema-to-ts.js +191 -0
  184. package/dist/schema-to-ts.js.map +1 -0
  185. package/dist/session.d.ts +23 -0
  186. package/dist/session.d.ts.map +1 -0
  187. package/dist/session.js +137 -0
  188. package/dist/session.js.map +1 -0
  189. package/dist/snapshot.d.ts +75 -0
  190. package/dist/snapshot.d.ts.map +1 -0
  191. package/dist/snapshot.js +1607 -0
  192. package/dist/snapshot.js.map +1 -0
  193. package/dist/steering.d.ts +75 -0
  194. package/dist/steering.d.ts.map +1 -0
  195. package/dist/steering.js +214 -0
  196. package/dist/steering.js.map +1 -0
  197. package/dist/subagents.d.ts +141 -0
  198. package/dist/subagents.d.ts.map +1 -0
  199. package/dist/subagents.js +746 -0
  200. package/dist/subagents.js.map +1 -0
  201. package/dist/tool-retry.d.ts +12 -0
  202. package/dist/tool-retry.d.ts.map +1 -0
  203. package/dist/tool-retry.js +53 -0
  204. package/dist/tool-retry.js.map +1 -0
  205. package/dist/tree.d.ts +98 -0
  206. package/dist/tree.d.ts.map +1 -0
  207. package/dist/tree.js +320 -0
  208. package/dist/tree.js.map +1 -0
  209. package/dist/types.d.ts +1007 -0
  210. package/dist/types.d.ts.map +1 -0
  211. package/dist/types.js +2 -0
  212. package/dist/types.js.map +1 -0
  213. package/dist/workflow-snapshot.d.ts +8 -0
  214. package/dist/workflow-snapshot.d.ts.map +1 -0
  215. package/dist/workflow-snapshot.js +276 -0
  216. package/dist/workflow-snapshot.js.map +1 -0
  217. package/dist/workflow-types.d.ts +171 -0
  218. package/dist/workflow-types.d.ts.map +1 -0
  219. package/dist/workflow-types.js +2 -0
  220. package/dist/workflow-types.js.map +1 -0
  221. package/dist/workflow.d.ts +19 -0
  222. package/dist/workflow.d.ts.map +1 -0
  223. package/dist/workflow.js +1053 -0
  224. package/dist/workflow.js.map +1 -0
  225. package/examples/a2a-remote.ts +85 -0
  226. package/examples/a2a-server.ts +100 -0
  227. package/examples/background.ts +59 -0
  228. package/examples/basic.ts +44 -0
  229. package/examples/code-mode.ts +76 -0
  230. package/examples/conversation.ts +57 -0
  231. package/examples/evals.ts +79 -0
  232. package/examples/guardrails.ts +56 -0
  233. package/examples/handoff.ts +79 -0
  234. package/examples/memory.ts +44 -0
  235. package/examples/otel.ts +99 -0
  236. package/examples/specialists.ts +99 -0
  237. package/examples/steering.ts +69 -0
  238. package/examples/structured-handoff.ts +92 -0
  239. package/examples/subagents.ts +127 -0
  240. package/examples/workflow.ts +74 -0
  241. package/package.json +114 -4
  242. package/src/a2a/auth.ts +62 -0
  243. package/src/a2a/client.ts +733 -0
  244. package/src/a2a/index.ts +74 -0
  245. package/src/a2a/memory-runs.ts +448 -0
  246. package/src/a2a/policy.ts +148 -0
  247. package/src/a2a/push.ts +251 -0
  248. package/src/a2a/remote.ts +1652 -0
  249. package/src/a2a/server.ts +1390 -0
  250. package/src/a2a/signing.ts +348 -0
  251. package/src/a2a/tasks.ts +260 -0
  252. package/src/a2a/wire.ts +1443 -0
  253. package/src/background-types.ts +86 -0
  254. package/src/child.ts +181 -0
  255. package/src/code-driver.ts +48 -0
  256. package/src/code-mode.ts +12 -0
  257. package/src/code-script.ts +149 -0
  258. package/src/code.ts +424 -0
  259. package/src/compaction.ts +212 -0
  260. package/src/delegation.ts +694 -0
  261. package/src/evals/driver.ts +222 -0
  262. package/src/evals/journal.ts +605 -0
  263. package/src/evals/judge.ts +188 -0
  264. package/src/evals/report.ts +295 -0
  265. package/src/evals/runner.ts +826 -0
  266. package/src/evals/scorers.ts +339 -0
  267. package/src/evals/simulation.ts +46 -0
  268. package/src/evals/testing.ts +126 -0
  269. package/src/evals/trajectory.ts +223 -0
  270. package/src/evals/types.ts +463 -0
  271. package/src/evals.ts +72 -0
  272. package/src/extensions.ts +247 -0
  273. package/src/handoff.ts +214 -0
  274. package/src/index.ts +62 -0
  275. package/src/input.ts +319 -0
  276. package/src/mcp.ts +690 -0
  277. package/src/memory-store.ts +366 -0
  278. package/src/memory.ts +893 -0
  279. package/src/otel.ts +568 -0
  280. package/src/progress.ts +214 -0
  281. package/src/quickjs.ts +524 -0
  282. package/src/recovery.ts +90 -0
  283. package/src/request.ts +513 -0
  284. package/src/run.ts +3199 -0
  285. package/src/runs.ts +696 -0
  286. package/src/schema-to-ts.ts +194 -0
  287. package/src/session.ts +178 -0
  288. package/src/snapshot.ts +2099 -0
  289. package/src/steering.ts +329 -0
  290. package/src/subagents.ts +1084 -0
  291. package/src/tool-retry.ts +86 -0
  292. package/src/tree.ts +366 -0
  293. package/src/types.ts +944 -0
  294. package/src/workflow-snapshot.ts +366 -0
  295. package/src/workflow-types.ts +213 -0
  296. package/src/workflow.ts +1316 -0
@@ -0,0 +1,1443 @@
1
+ // Version mappings adapted from Mastra's packages/core/src/a2a/compat/v1.ts.
2
+ // Copyright (c) 2025 Kepler Software, Inc. SPDX-License-Identifier: Apache-2.0
3
+ // Wire fields checked against a2aproject/A2A v1.0.0 and v0.3.0 schemas.
4
+ // The legacy HTTP binding uses protobuf JSON, not the legacy JSON-RPC shapes.
5
+
6
+ export type A2AVersion = "1.0" | "0.3";
7
+ export type A2ABinding = "JSONRPC" | "HTTP+JSON";
8
+ export interface A2ADialect {
9
+ version: A2AVersion;
10
+ binding: A2ABinding;
11
+ }
12
+ /** The specification assigns an omitted version header to 0.3. No automatic fallback. */
13
+ export function parseA2AVersion(header?: string | null): A2AVersion {
14
+ if (!header || header === "0.3") return "0.3";
15
+ if (header === "1.0") return "1.0";
16
+ throw new A2AError("protocol", { code: -32009 });
17
+ }
18
+ export type A2AJson = null | boolean | number | string | A2AJson[] | A2AObject;
19
+ export interface A2AObject {
20
+ [key: string]: A2AJson;
21
+ }
22
+ export type A2AState =
23
+ | "unknown"
24
+ | "submitted"
25
+ | "working"
26
+ | "completed"
27
+ | "failed"
28
+ | "canceled"
29
+ | "input_required"
30
+ | "rejected"
31
+ | "auth_required";
32
+ export type A2AErrorKind =
33
+ | "protocol"
34
+ | "invalid"
35
+ | "limit"
36
+ | "endpoint"
37
+ | "http"
38
+ | "network"
39
+ | "timeout"
40
+ | "stream-cut";
41
+ export type A2AOutcome = "not-sent" | "unknown" | "read";
42
+
43
+ const errorText: Record<A2AErrorKind, string> = {
44
+ protocol: "The peer refused the A2A request. Check the protocol error code.",
45
+ invalid: "The A2A data is invalid. Check the selected version and binding.",
46
+ limit: "The A2A data exceeds the configured limit. Use a smaller payload.",
47
+ endpoint: "The A2A endpoint is not allowed. Check the host's endpoint policy.",
48
+ http: "The A2A request failed. Check the HTTP status and server access.",
49
+ network: "The A2A connection failed. Read the task state before sending more work.",
50
+ timeout: "The A2A request timed out. Read the task state before sending more work.",
51
+ "stream-cut":
52
+ "The A2A stream ended before the task paused or finished. Read or subscribe to the task again.",
53
+ };
54
+
55
+ /** Never retains peer prose, a URL, a body, headers or an underlying exception. */
56
+ export class A2AError extends Error {
57
+ readonly kind: A2AErrorKind;
58
+ readonly code?: number;
59
+ readonly status?: number;
60
+ readonly outcome: A2AOutcome;
61
+ readonly retryable = false;
62
+ constructor(
63
+ kind: A2AErrorKind,
64
+ options: { code?: number; status?: number; outcome?: A2AOutcome } = {},
65
+ ) {
66
+ super(errorText[kind]);
67
+ this.name = "A2AError";
68
+ this.kind = kind;
69
+ this.code = options.code;
70
+ this.status = options.status;
71
+ this.outcome = options.outcome ?? "not-sent";
72
+ }
73
+ }
74
+
75
+ export interface A2ALimits {
76
+ bodyBytes: number;
77
+ depth: number;
78
+ nodes: number;
79
+ parts: number;
80
+ items: number;
81
+ textChars: number;
82
+ }
83
+ export const A2A_LIMITS: Readonly<A2ALimits> = Object.freeze({
84
+ bodyBytes: 8 * 1024 * 1024,
85
+ depth: 32,
86
+ nodes: 100_000,
87
+ parts: 64,
88
+ items: 1000,
89
+ textChars: 1024 * 1024,
90
+ });
91
+
92
+ export function a2aLimits(limits: Partial<A2ALimits> = {}): A2ALimits {
93
+ const result = { ...A2A_LIMITS, ...limits };
94
+ if (Object.values(result).some((n) => !Number.isSafeInteger(n) || n < 1))
95
+ throw new A2AError("invalid");
96
+ return result;
97
+ }
98
+ function invalid(): never {
99
+ throw new A2AError("invalid", { code: -32602 });
100
+ }
101
+ function unsupported(): never {
102
+ throw new A2AError("protocol", { code: -32004 });
103
+ }
104
+ function obj(value: unknown): A2AObject {
105
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid();
106
+ // All external entry points first run checkJson, so this assertion adds no trust.
107
+ return value as A2AObject;
108
+ }
109
+ function str(value: unknown, max = 2048, empty = false): string {
110
+ if (typeof value !== "string" || value.length > max || (!empty && !value.length))
111
+ return invalid();
112
+ return value;
113
+ }
114
+ function optionalString(value: unknown, max = 2048): string | undefined {
115
+ return value === undefined ? undefined : str(value, max, true);
116
+ }
117
+ function id(value: unknown): string {
118
+ return str(value, 512);
119
+ }
120
+ function optionalId(value: unknown): string | undefined {
121
+ return value === undefined || value === "" ? undefined : id(value);
122
+ }
123
+ function bool(value: unknown): boolean | undefined {
124
+ if (value === undefined) return undefined;
125
+ if (typeof value !== "boolean") return invalid();
126
+ return value;
127
+ }
128
+ function integer(value: unknown, min = 0, max = 2_147_483_647): number {
129
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max)
130
+ return invalid();
131
+ return value;
132
+ }
133
+ function list(value: unknown, max: number, nonempty = false): A2AJson[] {
134
+ if (!Array.isArray(value) || value.length > max || (nonempty && !value.length)) return invalid();
135
+ return value;
136
+ }
137
+ function strings(value: unknown, max: number): string[] {
138
+ return list(value, max).map((s) => str(s));
139
+ }
140
+ function metadata(value: unknown): A2AObject | undefined {
141
+ return value === undefined ? undefined : obj(value);
142
+ }
143
+ function optionalStrings(value: unknown, max: number): string[] | undefined {
144
+ return value === undefined ? undefined : strings(value, max);
145
+ }
146
+ function oneOf(value: A2AObject, keys: readonly string[]): string {
147
+ const present = keys.filter((key) => Object.hasOwn(value, key));
148
+ if (present.length !== 1) return invalid();
149
+ return present[0]!;
150
+ }
151
+ function clean(value: Record<string, A2AJson | undefined>): A2AObject {
152
+ return Object.fromEntries(
153
+ Object.entries(value).filter((entry): entry is [string, A2AJson] => entry[1] !== undefined),
154
+ );
155
+ }
156
+ function checkJson(value: unknown, limits: A2ALimits): asserts value is A2AJson {
157
+ const pending = [{ value, depth: 0 }];
158
+ let count = 0;
159
+ while (pending.length) {
160
+ const current = pending.pop()!;
161
+ if (++count > limits.nodes || current.depth > limits.depth) throw new A2AError("limit");
162
+ const v = current.value;
163
+ if (v === null || typeof v === "string" || typeof v === "boolean") continue;
164
+ if (typeof v === "number" && Number.isFinite(v)) continue;
165
+ if (
166
+ !v ||
167
+ typeof v !== "object" ||
168
+ (!Array.isArray(v) &&
169
+ Object.getPrototypeOf(v) !== Object.prototype &&
170
+ Object.getPrototypeOf(v) !== null)
171
+ )
172
+ return invalid();
173
+ for (const child of Object.values(v)) pending.push({ value: child, depth: current.depth + 1 });
174
+ if (pending.length + count > limits.nodes) throw new A2AError("limit");
175
+ }
176
+ }
177
+ /** JSON.parse validates grammar but discards duplicate members. Scan only the already-valid
178
+ * tokens so conflicting approval fields cannot be silently reduced to the last value. */
179
+ function uniqueJsonMembers(text: string): void {
180
+ const objects: (Set<string> | undefined)[] = [];
181
+ for (const match of text.matchAll(/"(?:\\.|[^"\\])*"|[{}[\]]/g)) {
182
+ const token = match[0];
183
+ if (token === "{") objects.push(new Set());
184
+ else if (token === "[") objects.push(undefined);
185
+ else if (token === "}" || token === "]") objects.pop();
186
+ else {
187
+ let next = match.index + token.length;
188
+ while (
189
+ text[next] === " " ||
190
+ text[next] === "\t" ||
191
+ text[next] === "\r" ||
192
+ text[next] === "\n"
193
+ )
194
+ next++;
195
+ if (text[next] !== ":") continue;
196
+ const names = objects.at(-1);
197
+ const name: unknown = JSON.parse(token);
198
+ if (!names || typeof name !== "string" || names.has(name)) return invalid();
199
+ names.add(name);
200
+ }
201
+ }
202
+ }
203
+
204
+ export function parseA2AJson(text: string, overrides?: Partial<A2ALimits>): A2AJson {
205
+ const limits = a2aLimits(overrides);
206
+ if (
207
+ text.length > limits.bodyBytes ||
208
+ new TextEncoder().encode(text).byteLength > limits.bodyBytes
209
+ )
210
+ throw new A2AError("limit");
211
+ let value: unknown;
212
+ try {
213
+ value = JSON.parse(text);
214
+ } catch {
215
+ throw new A2AError("protocol", { code: -32700 });
216
+ }
217
+ checkJson(value, limits);
218
+ uniqueJsonMembers(text);
219
+ return value;
220
+ }
221
+ function checked(value: unknown, limits: A2ALimits): A2AJson {
222
+ checkJson(value, limits);
223
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limits.bodyBytes)
224
+ throw new A2AError("limit");
225
+ return value;
226
+ }
227
+ function input(value: unknown, limits: A2ALimits): A2AObject {
228
+ return obj(checked(value, limits));
229
+ }
230
+ function legacyRpc(d: A2ADialect): boolean {
231
+ return d.version === "0.3" && d.binding === "JSONRPC";
232
+ }
233
+ function legacyRest(d: A2ADialect): boolean {
234
+ return d.version === "0.3" && d.binding === "HTTP+JSON";
235
+ }
236
+
237
+ interface PartFields {
238
+ metadata?: A2AObject;
239
+ filename?: string;
240
+ mediaType?: string;
241
+ }
242
+ export type A2APart = PartFields &
243
+ (
244
+ | { kind: "text"; text: string }
245
+ | { kind: "raw"; raw: string }
246
+ | { kind: "url"; url: string }
247
+ | { kind: "data"; data: A2AJson }
248
+ );
249
+ export interface A2AMessage {
250
+ kind: "message";
251
+ messageId: string;
252
+ role: "user" | "agent";
253
+ parts: A2APart[];
254
+ taskId?: string;
255
+ contextId?: string;
256
+ metadata?: A2AObject;
257
+ extensions?: string[];
258
+ referenceTaskIds?: string[];
259
+ }
260
+ export interface A2AArtifact {
261
+ artifactId: string;
262
+ parts: A2APart[];
263
+ name?: string;
264
+ description?: string;
265
+ metadata?: A2AObject;
266
+ extensions?: string[];
267
+ }
268
+ export interface A2AStatus {
269
+ state: A2AState;
270
+ message?: A2AMessage;
271
+ timestamp?: string;
272
+ }
273
+ export interface A2ATask {
274
+ kind: "task";
275
+ id: string;
276
+ contextId?: string;
277
+ status: A2AStatus;
278
+ artifacts?: A2AArtifact[];
279
+ history?: A2AMessage[];
280
+ metadata?: A2AObject;
281
+ }
282
+ export interface A2AStatusUpdate {
283
+ kind: "status-update";
284
+ taskId: string;
285
+ contextId: string;
286
+ status: A2AStatus;
287
+ final?: boolean;
288
+ metadata?: A2AObject;
289
+ }
290
+ export interface A2AArtifactUpdate {
291
+ kind: "artifact-update";
292
+ taskId: string;
293
+ contextId: string;
294
+ artifact: A2AArtifact;
295
+ append?: boolean;
296
+ lastChunk?: boolean;
297
+ metadata?: A2AObject;
298
+ }
299
+ export type A2AEvent = A2ATask | A2AMessage | A2AStatusUpdate | A2AArtifactUpdate;
300
+ export interface A2APushConfig {
301
+ taskId?: string;
302
+ id?: string;
303
+ url: string;
304
+ token?: string;
305
+ authentication?: { schemes: string[]; credentials?: string };
306
+ tenant?: string;
307
+ }
308
+ export interface A2AInterface {
309
+ url: string;
310
+ binding: string;
311
+ version: string;
312
+ tenant?: string;
313
+ }
314
+ export interface A2AAgentCard {
315
+ /** Original public fields, including security declarations and signatures. Untrusted, not authority. */
316
+ document: A2AObject;
317
+ version: A2AVersion;
318
+ interfaces: A2AInterface[];
319
+ capabilities: {
320
+ streaming?: boolean;
321
+ pushNotifications?: boolean;
322
+ extendedAgentCard?: boolean;
323
+ extensions?: { uri: string; required?: boolean }[];
324
+ };
325
+ }
326
+
327
+ const states: A2AState[] = [
328
+ "unknown",
329
+ "submitted",
330
+ "working",
331
+ "completed",
332
+ "failed",
333
+ "canceled",
334
+ "input_required",
335
+ "rejected",
336
+ "auth_required",
337
+ ];
338
+ export function a2aStateClosed(state: A2AState): boolean {
339
+ return !["unknown", "submitted", "working"].includes(state);
340
+ }
341
+ function stateFrom(value: unknown, d: A2ADialect): A2AState {
342
+ const index = states.findIndex((state) => stateTo(state, d) === value);
343
+ // Protobuf JSON parsers must also accept numeric enum values.
344
+ if (!legacyRpc(d) && typeof value === "number" && Number.isInteger(value) && states[value])
345
+ return states[value];
346
+ if (index < 0) return invalid();
347
+ return states[index]!;
348
+ }
349
+ function stateTo(state: A2AState, d: A2ADialect): string {
350
+ if (legacyRpc(d)) return state.replaceAll("_", "-");
351
+ return `TASK_STATE_${state === "unknown" ? "UNSPECIFIED" : state === "canceled" && legacyRest(d) ? "CANCELLED" : state.toUpperCase()}`;
352
+ }
353
+ function base64(value: unknown, limits: A2ALimits): string {
354
+ const s = str(value, limits.bodyBytes, true);
355
+ // Protobuf JSON permits URL-safe and unpadded base64 too. Do not decode or fetch media here.
356
+ if (
357
+ !/^[A-Za-z0-9+/_-]*={0,2}$/.test(s) ||
358
+ s.replace(/=+$/, "").length % 4 === 1 ||
359
+ (s.includes("=") && s.length % 4 !== 0)
360
+ )
361
+ return invalid();
362
+ return s;
363
+ }
364
+ function partFrom(value: unknown, d: A2ADialect, limits: A2ALimits): A2APart {
365
+ const p = obj(value);
366
+ const fields = {
367
+ metadata: metadata(p.metadata),
368
+ filename: optionalString(p.filename),
369
+ mediaType: optionalString(p.mediaType),
370
+ };
371
+ if (legacyRpc(d)) {
372
+ if (p.kind === "text")
373
+ return { ...fields, kind: "text", text: str(p.text, limits.textChars, true) };
374
+ if (p.kind === "data") return { ...fields, kind: "data", data: obj(p.data) };
375
+ if (p.kind !== "file") return invalid();
376
+ const f = obj(p.file);
377
+ const fileFields = {
378
+ ...fields,
379
+ filename: optionalString(f.name),
380
+ mediaType: optionalString(f.mimeType),
381
+ };
382
+ return oneOf(f, ["bytes", "uri"]) === "bytes"
383
+ ? { ...fileFields, kind: "raw", raw: base64(f.bytes, limits) }
384
+ : { ...fileFields, kind: "url", url: str(f.uri) };
385
+ }
386
+ const kind = oneOf(p, legacyRest(d) ? ["text", "file", "data"] : ["text", "raw", "url", "data"]);
387
+ if (kind === "text") return { ...fields, kind, text: str(p.text, limits.textChars, true) };
388
+ if (kind === "raw") return { ...fields, kind, raw: base64(p.raw, limits) };
389
+ if (kind === "url") return { ...fields, kind, url: str(p.url) };
390
+ if (kind === "data")
391
+ return { ...fields, kind, data: legacyRest(d) ? obj(obj(p.data).data) : p.data! };
392
+ const f = obj(p.file);
393
+ const fileFields = { mediaType: optionalString(f.mimeType) };
394
+ return oneOf(f, ["fileWithBytes", "fileWithUri"]) === "fileWithBytes"
395
+ ? { ...fileFields, kind: "raw", raw: base64(f.fileWithBytes, limits) }
396
+ : { ...fileFields, kind: "url", url: str(f.fileWithUri) };
397
+ }
398
+ function partTo(p: A2APart, d: A2ADialect): A2AObject {
399
+ const fields = clean({ metadata: p.metadata, filename: p.filename, mediaType: p.mediaType });
400
+ if (legacyRest(d)) {
401
+ if (p.metadata || p.filename || (p.mediaType && p.kind !== "raw" && p.kind !== "url"))
402
+ return unsupported();
403
+ if (p.kind === "text") return { text: p.text };
404
+ if (p.kind === "data") return { data: { data: obj(p.data) } };
405
+ return {
406
+ file: clean({
407
+ [p.kind === "raw" ? "fileWithBytes" : "fileWithUri"]: p.kind === "raw" ? p.raw : p.url,
408
+ mimeType: p.mediaType,
409
+ }),
410
+ };
411
+ }
412
+ if (legacyRpc(d)) {
413
+ if (p.kind === "text" || p.kind === "data") {
414
+ if (p.filename || p.mediaType) return unsupported();
415
+ return clean({
416
+ kind: p.kind,
417
+ [p.kind]: p.kind === "text" ? p.text : obj(p.data),
418
+ metadata: p.metadata,
419
+ });
420
+ }
421
+ return clean({
422
+ kind: "file",
423
+ file: clean({
424
+ [p.kind === "raw" ? "bytes" : "uri"]: p.kind === "raw" ? p.raw : p.url,
425
+ name: p.filename,
426
+ mimeType: p.mediaType,
427
+ }),
428
+ metadata: p.metadata,
429
+ });
430
+ }
431
+ return {
432
+ ...fields,
433
+ [p.kind]:
434
+ p.kind === "text" ? p.text : p.kind === "raw" ? p.raw : p.kind === "url" ? p.url : p.data,
435
+ };
436
+ }
437
+ function messageFrom(value: unknown, d: A2ADialect, l: A2ALimits): A2AMessage {
438
+ const m = obj(value);
439
+ if (legacyRpc(d) && m.kind !== "message") return invalid();
440
+ const user = legacyRpc(d) ? m.role === "user" : m.role === "ROLE_USER" || m.role === 1;
441
+ const agent = legacyRpc(d) ? m.role === "agent" : m.role === "ROLE_AGENT" || m.role === 2;
442
+ if (!user && !agent) return invalid();
443
+ return {
444
+ kind: "message",
445
+ messageId: str(m.messageId, 128),
446
+ role: user ? "user" : "agent",
447
+ parts: list(m[legacyRest(d) ? "content" : "parts"], l.parts, true).map((p) =>
448
+ partFrom(p, d, l),
449
+ ),
450
+ taskId: optionalId(m.taskId),
451
+ contextId: optionalId(m.contextId),
452
+ metadata: metadata(m.metadata),
453
+ extensions: optionalStrings(m.extensions, l.items),
454
+ referenceTaskIds: optionalStrings(m.referenceTaskIds, l.items),
455
+ };
456
+ }
457
+ function messageTo(m: A2AMessage, d: A2ADialect): A2AObject {
458
+ if (legacyRest(d) && m.referenceTaskIds?.length) return unsupported();
459
+ return clean({
460
+ kind: legacyRpc(d) ? "message" : undefined,
461
+ messageId: m.messageId,
462
+ role: legacyRpc(d) ? m.role : m.role === "user" ? "ROLE_USER" : "ROLE_AGENT",
463
+ [legacyRest(d) ? "content" : "parts"]: m.parts.map((p) => partTo(p, d)),
464
+ taskId: m.taskId,
465
+ contextId: m.contextId,
466
+ metadata: m.metadata,
467
+ extensions: m.extensions,
468
+ referenceTaskIds: legacyRest(d) ? undefined : m.referenceTaskIds,
469
+ });
470
+ }
471
+ function artifactFrom(value: unknown, d: A2ADialect, l: A2ALimits): A2AArtifact {
472
+ const a = obj(value);
473
+ return {
474
+ artifactId: id(a.artifactId),
475
+ parts: list(a.parts, l.parts, true).map((p) => partFrom(p, d, l)),
476
+ name: optionalString(a.name),
477
+ description: optionalString(a.description, l.textChars),
478
+ metadata: metadata(a.metadata),
479
+ extensions: optionalStrings(a.extensions, l.items),
480
+ };
481
+ }
482
+ function artifactTo(a: A2AArtifact, d: A2ADialect): A2AObject {
483
+ return clean({
484
+ artifactId: a.artifactId,
485
+ parts: a.parts.map((p) => partTo(p, d)),
486
+ name: a.name,
487
+ description: a.description,
488
+ metadata: a.metadata,
489
+ extensions: a.extensions,
490
+ });
491
+ }
492
+ function statusFrom(value: unknown, d: A2ADialect, l: A2ALimits): A2AStatus {
493
+ const s = obj(value);
494
+ const timestamp = optionalString(s.timestamp, 128);
495
+ if (
496
+ timestamp &&
497
+ (!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?(?:Z|[+-]\d\d:\d\d)$/.test(timestamp) ||
498
+ !Number.isFinite(Date.parse(timestamp)))
499
+ )
500
+ return invalid();
501
+ return {
502
+ state: stateFrom(s.state, d),
503
+ message: s.message === undefined ? undefined : messageFrom(s.message, d, l),
504
+ timestamp,
505
+ };
506
+ }
507
+ function statusTo(s: A2AStatus, d: A2ADialect): A2AObject {
508
+ return clean({
509
+ state: stateTo(s.state, d),
510
+ message: s.message && messageTo(s.message, d),
511
+ timestamp: s.timestamp,
512
+ });
513
+ }
514
+ function matchMessage(m: A2AMessage | undefined, taskId: string, contextId?: string): void {
515
+ if (
516
+ m &&
517
+ ((m.taskId && m.taskId !== taskId) || (m.contextId && contextId && m.contextId !== contextId))
518
+ )
519
+ return invalid();
520
+ }
521
+ function taskFrom(value: unknown, d: A2ADialect, l: A2ALimits): A2ATask {
522
+ const t = obj(value);
523
+ if (legacyRpc(d) && t.kind !== "task") return invalid();
524
+ const task: A2ATask = {
525
+ kind: "task",
526
+ id: id(t.id),
527
+ contextId: d.version === "0.3" ? id(t.contextId) : optionalId(t.contextId),
528
+ status: statusFrom(t.status, d, l),
529
+ artifacts:
530
+ t.artifacts === undefined
531
+ ? undefined
532
+ : list(t.artifacts, l.items).map((a) => artifactFrom(a, d, l)),
533
+ history:
534
+ t.history === undefined
535
+ ? undefined
536
+ : list(t.history, l.items).map((m) => messageFrom(m, d, l)),
537
+ metadata: metadata(t.metadata),
538
+ };
539
+ if (new Set(task.artifacts?.map((a) => a.artifactId)).size !== (task.artifacts?.length ?? 0))
540
+ return invalid();
541
+ matchMessage(task.status.message, task.id, task.contextId);
542
+ for (const message of task.history ?? []) matchMessage(message, task.id, task.contextId);
543
+ return task;
544
+ }
545
+ function taskTo(t: A2ATask, d: A2ADialect): A2AObject {
546
+ return clean({
547
+ kind: legacyRpc(d) ? "task" : undefined,
548
+ id: t.id,
549
+ contextId: t.contextId,
550
+ status: statusTo(t.status, d),
551
+ artifacts: t.artifacts?.map((a) => artifactTo(a, d)),
552
+ history: t.history?.map((m) => messageTo(m, d)),
553
+ metadata: t.metadata,
554
+ });
555
+ }
556
+
557
+ export function decodeA2AMessage(
558
+ value: unknown,
559
+ dialect: A2ADialect,
560
+ overrides?: Partial<A2ALimits>,
561
+ ): A2AMessage {
562
+ const l = a2aLimits(overrides);
563
+ return messageFrom(input(value, l), dialect, l);
564
+ }
565
+ export function encodeA2AMessage(value: A2AMessage, dialect: A2ADialect): A2AObject {
566
+ const wire = messageTo(value, dialect);
567
+ decodeA2AMessage(wire, dialect);
568
+ return wire;
569
+ }
570
+ export function decodeA2ATask(
571
+ value: unknown,
572
+ dialect: A2ADialect,
573
+ overrides?: Partial<A2ALimits>,
574
+ ): A2ATask {
575
+ const l = a2aLimits(overrides);
576
+ return taskFrom(input(value, l), dialect, l);
577
+ }
578
+ export function encodeA2ATask(value: A2ATask, dialect: A2ADialect): A2AObject {
579
+ const wire = taskTo(value, dialect);
580
+ decodeA2ATask(wire, dialect);
581
+ return wire;
582
+ }
583
+ export function decodeA2AEvent(
584
+ value: unknown,
585
+ d: A2ADialect,
586
+ overrides?: Partial<A2ALimits>,
587
+ ): A2AEvent {
588
+ const l = a2aLimits(overrides);
589
+ let wire = input(value, l);
590
+ const kind = legacyRpc(d)
591
+ ? wire.kind
592
+ : oneOf(wire, ["task", "message", "statusUpdate", "artifactUpdate"]);
593
+ if (!legacyRpc(d)) wire = obj(wire[String(kind)]);
594
+ if (kind === "task") return taskFrom(wire, d, l);
595
+ if (kind === "message") {
596
+ const message = messageFrom(wire, d, l);
597
+ if (message.role !== "agent" || !message.contextId) return invalid();
598
+ return message;
599
+ }
600
+ const fields = {
601
+ taskId: id(wire.taskId),
602
+ contextId: id(wire.contextId),
603
+ metadata: metadata(wire.metadata),
604
+ };
605
+ if (kind === "status-update" || kind === "statusUpdate") {
606
+ const status = statusFrom(wire.status, d, l);
607
+ matchMessage(status.message, fields.taskId, fields.contextId);
608
+ const final = d.version === "0.3" ? bool(wire.final) : undefined;
609
+ if (legacyRpc(d) && final === undefined) return invalid();
610
+ if (final === true && !a2aStateClosed(status.state)) return invalid();
611
+ return { kind: "status-update", ...fields, status, final };
612
+ }
613
+ if (kind !== "artifact-update" && kind !== "artifactUpdate") return invalid();
614
+ return {
615
+ kind: "artifact-update",
616
+ ...fields,
617
+ artifact: artifactFrom(wire.artifact, d, l),
618
+ append: bool(wire.append),
619
+ lastChunk: bool(wire.lastChunk),
620
+ };
621
+ }
622
+ export function encodeA2AEvent(event: A2AEvent, d: A2ADialect): A2AObject {
623
+ let wire: A2AObject;
624
+ let key: string;
625
+ if (event.kind === "task") {
626
+ wire = taskTo(event, d);
627
+ key = "task";
628
+ } else if (event.kind === "message") {
629
+ wire = messageTo(event, d);
630
+ key = "message";
631
+ } else {
632
+ key = event.kind === "status-update" ? "statusUpdate" : "artifactUpdate";
633
+ wire = clean({
634
+ kind: legacyRpc(d) ? event.kind : undefined,
635
+ taskId: event.taskId,
636
+ contextId: event.contextId,
637
+ metadata: event.metadata,
638
+ ...(event.kind === "status-update"
639
+ ? {
640
+ status: statusTo(event.status, d),
641
+ final: d.version === "0.3" ? a2aStateClosed(event.status.state) : undefined,
642
+ }
643
+ : {
644
+ artifact: artifactTo(event.artifact, d),
645
+ append: event.append,
646
+ lastChunk: event.lastChunk,
647
+ }),
648
+ });
649
+ }
650
+ const result = legacyRpc(d) ? wire : { [key]: wire };
651
+ decodeA2AEvent(result, d);
652
+ return result;
653
+ }
654
+
655
+ /** Keep public card fields verbatim. Signing and security interpretation belong to the host. */
656
+ export function decodeA2AAgentCard(
657
+ value: unknown,
658
+ version: A2AVersion,
659
+ overrides?: Partial<A2ALimits>,
660
+ ): A2AAgentCard {
661
+ const l = a2aLimits(overrides);
662
+ const card = input(value, l);
663
+ // ProtoJSON omits empty repeated/scalar defaults. Legacy JSON Schema requires these fields.
664
+ const repeated = (field: A2AJson | undefined) =>
665
+ version === "1.0" && field == null ? [] : field;
666
+ const description = (field: A2AJson | undefined) =>
667
+ version === "1.0" && field == null ? "" : field;
668
+ str(card.name);
669
+ str(description(card.description), l.textChars, true);
670
+ str(card.version);
671
+ strings(repeated(card.defaultInputModes), l.items);
672
+ strings(repeated(card.defaultOutputModes), l.items);
673
+ for (const skill of list(repeated(card.skills), l.items)) {
674
+ const s = obj(skill);
675
+ id(s.id);
676
+ str(s.name);
677
+ str(description(s.description), l.textChars, true);
678
+ strings(repeated(s.tags), l.items);
679
+ optionalStrings(s.examples, l.items);
680
+ optionalStrings(s.inputModes, l.items);
681
+ optionalStrings(s.outputModes, l.items);
682
+ }
683
+ if (card.provider !== undefined) {
684
+ const p = obj(card.provider);
685
+ str(p.organization);
686
+ str(p.url);
687
+ }
688
+ for (const key of ["documentationUrl", "iconUrl"]) optionalString(card[key]);
689
+ if (card.securitySchemes !== undefined) obj(card.securitySchemes);
690
+ for (const key of ["security", "securityRequirements"]) {
691
+ if (card[key] !== undefined) for (const entry of list(card[key], l.items)) obj(entry);
692
+ }
693
+ if (card.signatures !== undefined)
694
+ for (const entry of list(card.signatures, l.items)) {
695
+ const signature = obj(entry);
696
+ str(signature.protected, l.textChars);
697
+ str(signature.signature, l.textChars);
698
+ metadata(signature.header);
699
+ }
700
+ const c = obj(card.capabilities);
701
+ const capabilities = {
702
+ streaming: bool(c.streaming),
703
+ pushNotifications: bool(c.pushNotifications),
704
+ extendedAgentCard: bool(
705
+ version === "1.0" ? c.extendedAgentCard : card.supportsAuthenticatedExtendedCard,
706
+ ),
707
+ extensions:
708
+ c.extensions === undefined
709
+ ? undefined
710
+ : list(c.extensions, l.items).map((ext) => {
711
+ const e = obj(ext);
712
+ optionalString(e.description, l.textChars);
713
+ metadata(e.params);
714
+ return { uri: str(e.uri), required: bool(e.required) };
715
+ }),
716
+ };
717
+ let interfaces: A2AInterface[];
718
+ if (version === "1.0") {
719
+ interfaces = list(card.supportedInterfaces, l.items, true).map((entry) => {
720
+ const i = obj(entry);
721
+ return {
722
+ url: str(i.url),
723
+ binding: str(i.protocolBinding),
724
+ version: str(i.protocolVersion, 32),
725
+ tenant: optionalId(i.tenant),
726
+ };
727
+ });
728
+ } else {
729
+ const protocolVersion = str(card.protocolVersion, 32);
730
+ if (!/^0\.3(?:\.\d+)?$/.test(protocolVersion)) throw new A2AError("protocol", { code: -32009 });
731
+ interfaces = [
732
+ {
733
+ url: str(card.url),
734
+ binding: card.preferredTransport === undefined ? "JSONRPC" : str(card.preferredTransport),
735
+ version: protocolVersion,
736
+ },
737
+ ...list(card.additionalInterfaces ?? [], l.items).map((entry) => {
738
+ const i = obj(entry);
739
+ return { url: str(i.url), binding: str(i.transport), version: protocolVersion };
740
+ }),
741
+ ];
742
+ }
743
+ return { document: card, version, interfaces, capabilities };
744
+ }
745
+
746
+ function pushFrom(value: unknown, d: A2ADialect, taskRequired = false): A2APushConfig {
747
+ const outer = obj(value);
748
+ let p = outer;
749
+ let taskId = optionalId(outer.taskId);
750
+ let configId: string | undefined;
751
+ if (d.version === "0.3" && taskRequired) {
752
+ p = obj(outer.pushNotificationConfig);
753
+ if (legacyRest(d)) {
754
+ const parts = str(outer.name).split("/");
755
+ if (parts.length !== 4 || parts[0] !== "tasks" || parts[2] !== "pushNotificationConfigs")
756
+ return invalid();
757
+ try {
758
+ taskId = id(decodeURIComponent(parts[1]!));
759
+ configId = optionalId(decodeURIComponent(parts[3]!));
760
+ } catch {
761
+ return invalid();
762
+ }
763
+ }
764
+ }
765
+ if (taskRequired) id(taskId);
766
+ const a = p.authentication === undefined ? undefined : obj(p.authentication);
767
+ const schemes = a ? (d.version === "1.0" ? [str(a.scheme)] : strings(a.schemes, 16)) : undefined;
768
+ if (schemes && !schemes.length) return invalid();
769
+ if (configId && p.id !== undefined && p.id !== configId) return invalid();
770
+ return {
771
+ taskId,
772
+ id: optionalId(p.id) ?? configId,
773
+ url: str(p.url),
774
+ token: optionalString(p.token, 8192),
775
+ tenant: optionalId(outer.tenant),
776
+ authentication:
777
+ a && schemes ? { schemes, credentials: optionalString(a.credentials, 8192) } : undefined,
778
+ };
779
+ }
780
+ function pushTo(p: A2APushConfig, d: A2ADialect, taskRequired = false): A2AObject {
781
+ if (
782
+ d.version === "1.0" &&
783
+ p.authentication?.schemes.length !== undefined &&
784
+ p.authentication.schemes.length !== 1
785
+ )
786
+ return unsupported();
787
+ const config = clean({
788
+ id: p.id,
789
+ url: p.url,
790
+ token: p.token,
791
+ authentication: p.authentication
792
+ ? clean({
793
+ [d.version === "1.0" ? "scheme" : "schemes"]:
794
+ d.version === "1.0" ? p.authentication.schemes[0] : p.authentication.schemes,
795
+ credentials: p.authentication.credentials,
796
+ })
797
+ : undefined,
798
+ });
799
+ if (d.version === "1.0") return clean({ ...config, taskId: p.taskId, tenant: p.tenant });
800
+ if (p.tenant) return unsupported();
801
+ if (!taskRequired) return config;
802
+ if (legacyRpc(d)) return clean({ taskId: p.taskId, pushNotificationConfig: config });
803
+ return {
804
+ name: `tasks/${encodeURIComponent(id(p.taskId))}/pushNotificationConfigs/${encodeURIComponent(p.id ?? "")}`,
805
+ pushNotificationConfig: config,
806
+ };
807
+ }
808
+
809
+ function historyFrom(value: unknown, d: A2ADialect): number | undefined {
810
+ if (value === undefined) return undefined;
811
+ const length = integer(value);
812
+ // The 0.3 REST proto uses zero for unlimited history. 1.0 uses zero for none.
813
+ return legacyRest(d) && length === 0 ? undefined : length;
814
+ }
815
+ function historyTo(value: number | undefined, d: A2ADialect): number | undefined {
816
+ if (legacyRest(d) && value === 0) return unsupported();
817
+ return value;
818
+ }
819
+
820
+ export interface A2ASendParams {
821
+ message: A2AMessage;
822
+ configuration?: {
823
+ acceptedOutputModes?: string[];
824
+ returnImmediately?: boolean;
825
+ historyLength?: number;
826
+ pushNotificationConfig?: A2APushConfig;
827
+ };
828
+ metadata?: A2AObject;
829
+ tenant?: string;
830
+ }
831
+ export interface A2ATaskParams {
832
+ id: string;
833
+ historyLength?: number;
834
+ metadata?: A2AObject;
835
+ tenant?: string;
836
+ }
837
+ export interface A2AListParams {
838
+ contextId?: string;
839
+ status?: A2AState;
840
+ pageSize?: number;
841
+ pageToken?: string;
842
+ historyLength?: number;
843
+ statusTimestampAfter?: string;
844
+ includeArtifacts?: boolean;
845
+ tenant?: string;
846
+ }
847
+ export interface A2APushParams {
848
+ taskId: string;
849
+ id?: string;
850
+ pageSize?: number;
851
+ pageToken?: string;
852
+ metadata?: A2AObject;
853
+ tenant?: string;
854
+ }
855
+ export interface A2ARequests {
856
+ SendMessage: A2ASendParams;
857
+ SendStreamingMessage: A2ASendParams;
858
+ GetTask: A2ATaskParams;
859
+ CancelTask: A2ATaskParams;
860
+ SubscribeToTask: A2ATaskParams;
861
+ ListTasks: A2AListParams;
862
+ CreateTaskPushNotificationConfig: A2APushConfig;
863
+ GetTaskPushNotificationConfig: A2APushParams;
864
+ ListTaskPushNotificationConfigs: A2APushParams;
865
+ DeleteTaskPushNotificationConfig: A2APushParams;
866
+ GetExtendedAgentCard: { tenant?: string };
867
+ }
868
+ export interface A2AResults {
869
+ SendMessage: A2ATask | A2AMessage;
870
+ SendStreamingMessage: A2AEvent;
871
+ GetTask: A2ATask;
872
+ CancelTask: A2ATask;
873
+ SubscribeToTask: A2AEvent;
874
+ ListTasks: { tasks: A2ATask[]; nextPageToken: string; pageSize: number; totalSize: number };
875
+ CreateTaskPushNotificationConfig: A2APushConfig;
876
+ GetTaskPushNotificationConfig: A2APushConfig;
877
+ ListTaskPushNotificationConfigs: { configs: A2APushConfig[]; nextPageToken?: string };
878
+ DeleteTaskPushNotificationConfig: null;
879
+ GetExtendedAgentCard: A2AAgentCard;
880
+ }
881
+ export type A2AMethod = keyof A2ARequests;
882
+ export type A2ARequest = { [M in A2AMethod]: { method: M; params: A2ARequests[M] } }[A2AMethod];
883
+ const legacyMethods: Record<A2AMethod, string> = {
884
+ SendMessage: "message/send",
885
+ SendStreamingMessage: "message/stream",
886
+ GetTask: "tasks/get",
887
+ CancelTask: "tasks/cancel",
888
+ SubscribeToTask: "tasks/resubscribe",
889
+ ListTasks: "tasks/list",
890
+ CreateTaskPushNotificationConfig: "tasks/pushNotificationConfig/set",
891
+ GetTaskPushNotificationConfig: "tasks/pushNotificationConfig/get",
892
+ ListTaskPushNotificationConfigs: "tasks/pushNotificationConfig/list",
893
+ DeleteTaskPushNotificationConfig: "tasks/pushNotificationConfig/delete",
894
+ GetExtendedAgentCard: "agent/getAuthenticatedExtendedCard",
895
+ };
896
+ export function a2aMethodName(method: A2AMethod, version: A2AVersion): string {
897
+ if (!Object.hasOwn(legacyMethods, method)) throw new A2AError("protocol", { code: -32601 });
898
+ if (method === "ListTasks" && version === "0.3") return unsupported();
899
+ return version === "1.0" ? method : legacyMethods[method];
900
+ }
901
+ export function a2aIsMutation(method: A2AMethod): boolean {
902
+ return [
903
+ "SendMessage",
904
+ "SendStreamingMessage",
905
+ "CancelTask",
906
+ "CreateTaskPushNotificationConfig",
907
+ "DeleteTaskPushNotificationConfig",
908
+ ].includes(method);
909
+ }
910
+
911
+ /** The name selects a method, not a version. Callers must select the dialect first. */
912
+ export function decodeA2ARequest(
913
+ methodName: string,
914
+ value: unknown,
915
+ d: A2ADialect,
916
+ overrides?: Partial<A2ALimits>,
917
+ ): A2ARequest {
918
+ const l = a2aLimits(overrides);
919
+ const p = input(value, l);
920
+ const method = (Object.keys(legacyMethods) as A2AMethod[]).find(
921
+ (m) => (d.version === "1.0" ? m : legacyMethods[m]) === methodName,
922
+ );
923
+ if (!method) throw new A2AError("protocol", { code: -32601 });
924
+ a2aMethodName(method, d.version);
925
+ const tenant = optionalId(p.tenant);
926
+ if (tenant && d.version !== "1.0") return unsupported();
927
+ switch (method) {
928
+ case "SendMessage":
929
+ case "SendStreamingMessage": {
930
+ const message = messageFrom(p.message, d, l);
931
+ if (message.role !== "user") return invalid();
932
+ const c = p.configuration === undefined ? undefined : obj(p.configuration);
933
+ const push =
934
+ c?.[
935
+ d.version === "1.0"
936
+ ? "taskPushNotificationConfig"
937
+ : legacyRest(d)
938
+ ? "pushNotification"
939
+ : "pushNotificationConfig"
940
+ ];
941
+ const blocking = c && bool(c[d.version === "1.0" ? "returnImmediately" : "blocking"]);
942
+ const configuration = c
943
+ ? {
944
+ acceptedOutputModes: optionalStrings(c.acceptedOutputModes, l.items),
945
+ returnImmediately:
946
+ blocking === undefined ? undefined : d.version === "1.0" ? blocking : !blocking,
947
+ historyLength: historyFrom(c.historyLength, d),
948
+ pushNotificationConfig: push === undefined ? undefined : pushFrom(push, d),
949
+ }
950
+ : undefined;
951
+ return { method, params: { message, configuration, metadata: metadata(p.metadata), tenant } };
952
+ }
953
+ case "GetTask":
954
+ case "CancelTask":
955
+ case "SubscribeToTask": {
956
+ if (method !== "GetTask" && p.historyLength !== undefined) return invalid();
957
+ if (
958
+ p.metadata !== undefined &&
959
+ (legacyRest(d) || (d.version === "1.0" && method !== "CancelTask"))
960
+ )
961
+ return unsupported();
962
+ let taskId = p.id;
963
+ if (legacyRest(d)) {
964
+ const name = str(p.name);
965
+ if (!name.startsWith("tasks/")) return invalid();
966
+ try {
967
+ taskId = decodeURIComponent(name.slice(6));
968
+ } catch {
969
+ return invalid();
970
+ }
971
+ }
972
+ return {
973
+ method,
974
+ params: {
975
+ id: id(taskId),
976
+ historyLength: historyFrom(p.historyLength, d),
977
+ metadata: metadata(p.metadata),
978
+ tenant,
979
+ },
980
+ };
981
+ }
982
+ case "ListTasks":
983
+ return {
984
+ method,
985
+ params: {
986
+ contextId: optionalId(p.contextId),
987
+ status: p.status === undefined ? undefined : stateFrom(p.status, d),
988
+ pageSize: p.pageSize === undefined ? undefined : integer(p.pageSize, 1, 100),
989
+ pageToken: optionalString(p.pageToken),
990
+ historyLength: historyFrom(p.historyLength, d),
991
+ statusTimestampAfter: optionalString(p.statusTimestampAfter, 128),
992
+ includeArtifacts: bool(p.includeArtifacts),
993
+ tenant,
994
+ },
995
+ };
996
+ case "CreateTaskPushNotificationConfig":
997
+ return { method, params: pushFrom(p, d, true) };
998
+ case "GetTaskPushNotificationConfig":
999
+ case "DeleteTaskPushNotificationConfig":
1000
+ case "ListTaskPushNotificationConfigs": {
1001
+ if (!legacyRpc(d) && p.metadata !== undefined) return unsupported();
1002
+ if (
1003
+ method !== "ListTaskPushNotificationConfigs" &&
1004
+ (p.pageSize !== undefined || p.pageToken !== undefined)
1005
+ )
1006
+ return invalid();
1007
+ let taskId = legacyRpc(d) ? p.id : p.taskId;
1008
+ let configId = legacyRpc(d) ? p.pushNotificationConfigId : p.id;
1009
+ if (legacyRest(d)) {
1010
+ const name = str(p.name ?? p.parent).split("/");
1011
+ if (
1012
+ name[0] !== "tasks" ||
1013
+ (method === "ListTaskPushNotificationConfigs"
1014
+ ? name.length !== 2
1015
+ : name.length !== 4 || name[2] !== "pushNotificationConfigs")
1016
+ )
1017
+ return invalid();
1018
+ try {
1019
+ taskId = decodeURIComponent(name[1]!);
1020
+ configId = name[3] && decodeURIComponent(name[3]);
1021
+ } catch {
1022
+ return invalid();
1023
+ }
1024
+ }
1025
+ const config = optionalId(configId);
1026
+ if (
1027
+ method !== "ListTaskPushNotificationConfigs" &&
1028
+ (d.version === "1.0" || method === "DeleteTaskPushNotificationConfig") &&
1029
+ !config
1030
+ )
1031
+ return invalid();
1032
+ return {
1033
+ method,
1034
+ params: {
1035
+ taskId: id(taskId),
1036
+ id: config,
1037
+ pageSize: p.pageSize === undefined ? undefined : integer(p.pageSize, 1, 100),
1038
+ pageToken: optionalString(p.pageToken),
1039
+ metadata: metadata(p.metadata),
1040
+ tenant,
1041
+ },
1042
+ };
1043
+ }
1044
+ case "GetExtendedAgentCard":
1045
+ return { method, params: { tenant } };
1046
+ }
1047
+ }
1048
+ export function encodeA2ARequest(
1049
+ request: A2ARequest,
1050
+ d: A2ADialect,
1051
+ overrides?: Partial<A2ALimits>,
1052
+ ): { method: string; params: A2AObject } {
1053
+ const method = a2aMethodName(request.method, d.version);
1054
+ const p = request.params;
1055
+ if (d.version === "0.3" && p.tenant) return unsupported();
1056
+ let params: A2AObject;
1057
+ switch (request.method) {
1058
+ case "SendMessage":
1059
+ case "SendStreamingMessage": {
1060
+ const s = request.params;
1061
+ const c = s.configuration;
1062
+ params = clean({
1063
+ message: messageTo(s.message, d),
1064
+ metadata: s.metadata,
1065
+ tenant: s.tenant,
1066
+ configuration: c
1067
+ ? clean({
1068
+ acceptedOutputModes: c.acceptedOutputModes,
1069
+ [d.version === "1.0" ? "returnImmediately" : "blocking"]:
1070
+ c.returnImmediately === undefined
1071
+ ? undefined
1072
+ : d.version === "1.0"
1073
+ ? c.returnImmediately
1074
+ : !c.returnImmediately,
1075
+ historyLength: historyTo(c.historyLength, d),
1076
+ [d.version === "1.0"
1077
+ ? "taskPushNotificationConfig"
1078
+ : legacyRest(d)
1079
+ ? "pushNotification"
1080
+ : "pushNotificationConfig"]:
1081
+ c.pushNotificationConfig && pushTo(c.pushNotificationConfig, d),
1082
+ })
1083
+ : undefined,
1084
+ });
1085
+ break;
1086
+ }
1087
+ case "GetTask":
1088
+ case "CancelTask":
1089
+ case "SubscribeToTask": {
1090
+ const t = request.params;
1091
+ params = clean({
1092
+ [legacyRest(d) ? "name" : "id"]: legacyRest(d) ? `tasks/${encodeURIComponent(t.id)}` : t.id,
1093
+ tenant: t.tenant,
1094
+ historyLength: historyTo(t.historyLength, d),
1095
+ metadata: t.metadata,
1096
+ });
1097
+ break;
1098
+ }
1099
+ case "ListTasks": {
1100
+ const t = request.params;
1101
+ params = clean({ ...t, status: t.status && stateTo(t.status, d) });
1102
+ break;
1103
+ }
1104
+ case "CreateTaskPushNotificationConfig":
1105
+ params = pushTo(request.params, d, true);
1106
+ break;
1107
+ case "GetTaskPushNotificationConfig":
1108
+ case "DeleteTaskPushNotificationConfig":
1109
+ case "ListTaskPushNotificationConfigs": {
1110
+ const t = request.params;
1111
+ if (legacyRest(d) && t.metadata !== undefined) return unsupported();
1112
+ if (legacyRpc(d) && (t.pageSize !== undefined || t.pageToken !== undefined))
1113
+ return unsupported();
1114
+ params = legacyRest(d)
1115
+ ? clean({
1116
+ [request.method === "ListTaskPushNotificationConfigs" ? "parent" : "name"]:
1117
+ `tasks/${encodeURIComponent(t.taskId)}${request.method === "ListTaskPushNotificationConfigs" ? "" : `/pushNotificationConfigs/${encodeURIComponent(id(t.id))}`}`,
1118
+ pageSize: t.pageSize,
1119
+ pageToken: t.pageToken,
1120
+ })
1121
+ : clean({
1122
+ [legacyRpc(d) ? "id" : "taskId"]: t.taskId,
1123
+ [legacyRpc(d) ? "pushNotificationConfigId" : "id"]: t.id,
1124
+ pageSize: t.pageSize,
1125
+ pageToken: t.pageToken,
1126
+ metadata: t.metadata,
1127
+ tenant: t.tenant,
1128
+ });
1129
+ break;
1130
+ }
1131
+ case "GetExtendedAgentCard":
1132
+ params = clean({ tenant: p.tenant });
1133
+ break;
1134
+ }
1135
+ decodeA2ARequest(method, params, d, overrides);
1136
+ return { method, params };
1137
+ }
1138
+
1139
+ /** Validates a result against its operation before the typed boundary assertion. */
1140
+ export function decodeA2AResult<M extends A2AMethod>(
1141
+ method: M,
1142
+ value: unknown,
1143
+ d: A2ADialect,
1144
+ overrides?: Partial<A2ALimits>,
1145
+ ): A2AResults[M] {
1146
+ const l = a2aLimits(overrides);
1147
+ a2aMethodName(method, d.version);
1148
+ checked(value, l);
1149
+ let result: A2AResults[A2AMethod];
1150
+ switch (method) {
1151
+ case "SendMessage": {
1152
+ const event = decodeA2AEvent(value, d, l);
1153
+ if (event.kind !== "task" && event.kind !== "message") return invalid();
1154
+ result = event;
1155
+ break;
1156
+ }
1157
+ case "SendStreamingMessage":
1158
+ case "SubscribeToTask":
1159
+ result = decodeA2AEvent(value, d, l);
1160
+ break;
1161
+ case "GetTask":
1162
+ case "CancelTask":
1163
+ result = taskFrom(value, d, l);
1164
+ break;
1165
+ case "ListTasks": {
1166
+ const p = obj(value);
1167
+ result = {
1168
+ tasks: list(p.tasks, l.items).map((t) => taskFrom(t, d, l)),
1169
+ nextPageToken: str(p.nextPageToken, 2048, true),
1170
+ pageSize: integer(p.pageSize, 0, 100),
1171
+ totalSize: integer(p.totalSize),
1172
+ };
1173
+ break;
1174
+ }
1175
+ case "CreateTaskPushNotificationConfig":
1176
+ case "GetTaskPushNotificationConfig":
1177
+ result = pushFrom(value, d, true);
1178
+ break;
1179
+ case "ListTaskPushNotificationConfigs": {
1180
+ const p = legacyRpc(d) ? undefined : obj(value);
1181
+ result = {
1182
+ configs: list(p ? (p.configs ?? []) : value, l.items).map((c) => pushFrom(c, d, true)),
1183
+ nextPageToken: p && optionalString(p.nextPageToken),
1184
+ };
1185
+ break;
1186
+ }
1187
+ case "DeleteTaskPushNotificationConfig":
1188
+ if (value !== null && (legacyRpc(d) || Object.keys(obj(value)).length)) return invalid();
1189
+ result = null;
1190
+ break;
1191
+ case "GetExtendedAgentCard":
1192
+ result = decodeA2AAgentCard(value, d.version, l);
1193
+ break;
1194
+ }
1195
+ // Each switch branch above validates the matching result, without a generic JSON cast.
1196
+ return result as A2AResults[M];
1197
+ }
1198
+
1199
+ export type A2AResponse = { [M in A2AMethod]: { method: M; result: A2AResults[M] } }[A2AMethod];
1200
+ export function encodeA2AResult(response: A2AResponse, d: A2ADialect): A2AJson {
1201
+ let result: A2AJson;
1202
+ switch (response.method) {
1203
+ case "SendMessage":
1204
+ case "SendStreamingMessage":
1205
+ case "SubscribeToTask":
1206
+ result = encodeA2AEvent(response.result, d);
1207
+ break;
1208
+ case "GetTask":
1209
+ case "CancelTask":
1210
+ result = taskTo(response.result, d);
1211
+ break;
1212
+ case "ListTasks":
1213
+ result = { ...response.result, tasks: response.result.tasks.map((t) => taskTo(t, d)) };
1214
+ break;
1215
+ case "CreateTaskPushNotificationConfig":
1216
+ case "GetTaskPushNotificationConfig":
1217
+ result = pushTo(response.result, d, true);
1218
+ break;
1219
+ case "ListTaskPushNotificationConfigs": {
1220
+ const configs = response.result.configs.map((p) => pushTo(p, d, true));
1221
+ result = legacyRpc(d)
1222
+ ? configs
1223
+ : clean({ configs, nextPageToken: response.result.nextPageToken });
1224
+ break;
1225
+ }
1226
+ case "DeleteTaskPushNotificationConfig":
1227
+ result = legacyRpc(d) ? null : {};
1228
+ break;
1229
+ case "GetExtendedAgentCard":
1230
+ if (response.result.version !== d.version) return unsupported();
1231
+ result = response.result.document;
1232
+ break;
1233
+ }
1234
+ decodeA2AResult(response.method, result, d);
1235
+ return result;
1236
+ }
1237
+
1238
+ export type A2ARpcId = string | number;
1239
+ function rpcId(value: unknown): A2ARpcId {
1240
+ if (typeof value === "string") return str(value, 512);
1241
+ if (typeof value === "number" && Number.isSafeInteger(value)) return value;
1242
+ return invalid();
1243
+ }
1244
+ export function decodeA2ARpcRequest(
1245
+ value: unknown,
1246
+ version: A2AVersion,
1247
+ overrides?: Partial<A2ALimits>,
1248
+ ): { id: A2ARpcId; request: A2ARequest } {
1249
+ const p = input(value, a2aLimits(overrides));
1250
+ if (p.jsonrpc !== "2.0") throw new A2AError("protocol", { code: -32600 });
1251
+ return {
1252
+ id: rpcId(p.id),
1253
+ request: decodeA2ARequest(
1254
+ str(p.method, 128),
1255
+ p.params ?? {},
1256
+ { version, binding: "JSONRPC" },
1257
+ overrides,
1258
+ ),
1259
+ };
1260
+ }
1261
+ export function decodeA2ARpcResponse(
1262
+ value: unknown,
1263
+ expectedId: A2ARpcId,
1264
+ overrides?: Partial<A2ALimits>,
1265
+ ): A2AJson {
1266
+ const p = input(value, a2aLimits(overrides));
1267
+ if (p.jsonrpc !== "2.0" || (p.id !== expectedId && !(p.id === null && Object.hasOwn(p, "error"))))
1268
+ return invalid();
1269
+ if (oneOf(p, ["result", "error"]) === "error") {
1270
+ const error = obj(p.error);
1271
+ const code = integer(error.code, -2_147_483_648);
1272
+ str(error.message, A2A_LIMITS.textChars, true);
1273
+ throw new A2AError("protocol", { code });
1274
+ }
1275
+ return p.result!;
1276
+ }
1277
+
1278
+ const protocolErrors: Record<number, [string, string, number]> = {
1279
+ [-32700]: ["Invalid JSON payload", "JSON_PARSE_ERROR", 400],
1280
+ [-32600]: ["Invalid request", "INVALID_REQUEST", 400],
1281
+ [-32601]: ["Method not found", "METHOD_NOT_FOUND", 404],
1282
+ [-32602]: ["Invalid parameters", "INVALID_PARAMS", 400],
1283
+ [-32603]: ["Internal error", "INTERNAL_ERROR", 500],
1284
+ [-32001]: ["Task not found", "TASK_NOT_FOUND", 404],
1285
+ [-32002]: ["Task cannot be canceled", "TASK_NOT_CANCELABLE", 400],
1286
+ [-32003]: ["Push notifications are not supported", "PUSH_NOTIFICATION_NOT_SUPPORTED", 400],
1287
+ [-32004]: ["Operation is not supported", "UNSUPPORTED_OPERATION", 400],
1288
+ [-32005]: ["Content type is not supported", "CONTENT_TYPE_NOT_SUPPORTED", 400],
1289
+ [-32006]: ["Invalid agent response", "INVALID_AGENT_RESPONSE", 500],
1290
+ [-32007]: ["Extended agent card is not configured", "EXTENDED_AGENT_CARD_NOT_CONFIGURED", 400],
1291
+ [-32008]: ["Required extension is not supported", "EXTENSION_SUPPORT_REQUIRED", 400],
1292
+ [-32009]: ["Version is not supported", "VERSION_NOT_SUPPORTED", 400],
1293
+ };
1294
+ export function encodeA2AError(
1295
+ code: number,
1296
+ d: A2ADialect,
1297
+ requestId: A2ARpcId | null = null,
1298
+ ): { status: number; body: A2AObject } {
1299
+ code = protocolErrors[code] ? code : -32603;
1300
+ const [message, reason, status] = protocolErrors[code]!;
1301
+ if (d.binding === "JSONRPC")
1302
+ return {
1303
+ status: 200,
1304
+ body: {
1305
+ jsonrpc: "2.0",
1306
+ id: requestId,
1307
+ error: { code, message },
1308
+ },
1309
+ };
1310
+ if (legacyRest(d)) return { status, body: { code, message } };
1311
+ return {
1312
+ status,
1313
+ body: {
1314
+ error: {
1315
+ code: status,
1316
+ message,
1317
+ status:
1318
+ status === 404
1319
+ ? "NOT_FOUND"
1320
+ : status === 500
1321
+ ? "INTERNAL"
1322
+ : [-32002, -32003, -32004, -32007, -32008, -32009].includes(code)
1323
+ ? "FAILED_PRECONDITION"
1324
+ : "INVALID_ARGUMENT",
1325
+ details: [
1326
+ {
1327
+ "@type": "type.googleapis.com/google.rpc.ErrorInfo",
1328
+ domain: "a2a-protocol.org",
1329
+ reason,
1330
+ },
1331
+ ],
1332
+ },
1333
+ },
1334
+ };
1335
+ }
1336
+ export function decodeA2AHttpError(
1337
+ value: unknown,
1338
+ status: number,
1339
+ overrides?: Partial<A2ALimits>,
1340
+ ): A2AError {
1341
+ const p = input(value, a2aLimits(overrides));
1342
+ const e = obj(p.error ?? p);
1343
+ // Some legacy REST servers send a JSON-RPC error object without its envelope.
1344
+ if (typeof e.code === "number" && e.code < 0 && Number.isSafeInteger(e.code))
1345
+ return new A2AError("protocol", { code: e.code, status });
1346
+ for (const detail of Array.isArray(e.details) ? e.details : []) {
1347
+ const entry = obj(detail);
1348
+ if (
1349
+ entry["@type"] !== "type.googleapis.com/google.rpc.ErrorInfo" ||
1350
+ entry.domain !== "a2a-protocol.org"
1351
+ )
1352
+ continue;
1353
+ const found = Object.entries(protocolErrors).find(([, data]) => data[1] === entry.reason);
1354
+ if (found) return new A2AError("protocol", { code: Number(found[0]), status });
1355
+ }
1356
+ return new A2AError("http", { status });
1357
+ }
1358
+
1359
+ /** One observation, not a durable run. Closing it never sends CancelTask. */
1360
+ export function createA2AStreamTracker(
1361
+ expected: { taskId?: string; contextId?: string } = {},
1362
+ maxResultBytes = 1024 * 1024,
1363
+ observation?: { method: "SendStreamingMessage" | "SubscribeToTask"; version: A2AVersion },
1364
+ ): { accept(event: A2AEvent): boolean } {
1365
+ integer(maxResultBytes, 1);
1366
+ // A 0.3 resubscription may send only updates, without repeating the known task.
1367
+ const updatesFirst =
1368
+ observation?.method === "SubscribeToTask" && observation.version === "0.3" && !!expected.taskId;
1369
+ let taskId = expected.taskId;
1370
+ let contextId = expected.contextId;
1371
+ let started = false;
1372
+ let closed = false;
1373
+ // Keep sizes and identity, not another copy of all streamed output. Tiny deltas
1374
+ // must not repeatedly copy and serialize the entire answer.
1375
+ const artifacts = new Map<
1376
+ string,
1377
+ { header: A2AObject; partsBytes: number; bytes: number; closed: boolean }
1378
+ >();
1379
+ const encoder = new TextEncoder();
1380
+ let totalBytes = 0;
1381
+ function record(artifact: A2AArtifact, append = false, lastChunk = false): void {
1382
+ const old = artifacts.get(artifact.artifactId);
1383
+ if (append && (!old || old.closed)) return invalid();
1384
+ const header = {
1385
+ ...(append ? old?.header : undefined),
1386
+ ...clean({
1387
+ artifactId: artifact.artifactId,
1388
+ name: artifact.name,
1389
+ description: artifact.description,
1390
+ metadata: artifact.metadata,
1391
+ extensions: artifact.extensions,
1392
+ }),
1393
+ };
1394
+ const partsBytes =
1395
+ encoder.encode(JSON.stringify(artifact.parts)).byteLength -
1396
+ 2 +
1397
+ (append && old ? old.partsBytes + 1 : 0);
1398
+ const bytes = encoder.encode(JSON.stringify({ ...header, parts: [] })).byteLength + partsBytes;
1399
+ totalBytes += bytes - (old?.bytes ?? 0);
1400
+ artifacts.set(artifact.artifactId, { header, partsBytes, bytes, closed: lastChunk });
1401
+ }
1402
+ function bound(): void {
1403
+ if (2 + totalBytes + Math.max(0, artifacts.size - 1) > maxResultBytes)
1404
+ throw new A2AError("limit");
1405
+ }
1406
+ return {
1407
+ accept(event) {
1408
+ if (closed) return invalid();
1409
+ if (!started && event.kind !== "task" && event.kind !== "message" && !updatesFirst)
1410
+ return invalid();
1411
+ if (event.kind === "message") {
1412
+ if (started || event.role !== "agent") return invalid();
1413
+ if ((taskId && event.taskId !== taskId) || (contextId && event.contextId !== contextId))
1414
+ return invalid();
1415
+ if (new TextEncoder().encode(JSON.stringify(event)).byteLength > maxResultBytes)
1416
+ throw new A2AError("limit");
1417
+ closed = true;
1418
+ return true;
1419
+ }
1420
+ const receivedId = event.kind === "task" ? event.id : event.taskId;
1421
+ if (
1422
+ (taskId && receivedId !== taskId) ||
1423
+ (contextId && event.contextId && contextId !== event.contextId)
1424
+ )
1425
+ return invalid();
1426
+ taskId = receivedId;
1427
+ contextId ??= event.contextId;
1428
+ started = true;
1429
+ if (event.kind === "task") {
1430
+ artifacts.clear();
1431
+ totalBytes = 0;
1432
+ for (const artifact of event.artifacts ?? []) record(artifact);
1433
+ closed = a2aStateClosed(event.status.state);
1434
+ } else if (event.kind === "status-update") {
1435
+ closed = a2aStateClosed(event.status.state);
1436
+ } else {
1437
+ record(event.artifact, event.append, event.lastChunk);
1438
+ }
1439
+ bound();
1440
+ return closed;
1441
+ },
1442
+ };
1443
+ }