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