@providerkit/agents 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. package/LICENSE-APACHE-2.0 +202 -0
  2. package/README.md +2108 -52
  3. package/THIRD_PARTY_NOTICES.md +521 -0
  4. package/dist/a2a/auth.d.ts +10 -0
  5. package/dist/a2a/auth.d.ts.map +1 -0
  6. package/dist/a2a/auth.js +52 -0
  7. package/dist/a2a/auth.js.map +1 -0
  8. package/dist/a2a/client.d.ts +74 -0
  9. package/dist/a2a/client.d.ts.map +1 -0
  10. package/dist/a2a/client.js +601 -0
  11. package/dist/a2a/client.js.map +1 -0
  12. package/dist/a2a/index.d.ts +22 -0
  13. package/dist/a2a/index.d.ts.map +1 -0
  14. package/dist/a2a/index.js +11 -0
  15. package/dist/a2a/index.js.map +1 -0
  16. package/dist/a2a/memory-runs.d.ts +62 -0
  17. package/dist/a2a/memory-runs.d.ts.map +1 -0
  18. package/dist/a2a/memory-runs.js +349 -0
  19. package/dist/a2a/memory-runs.js.map +1 -0
  20. package/dist/a2a/policy.d.ts +15 -0
  21. package/dist/a2a/policy.d.ts.map +1 -0
  22. package/dist/a2a/policy.js +114 -0
  23. package/dist/a2a/policy.js.map +1 -0
  24. package/dist/a2a/push.d.ts +34 -0
  25. package/dist/a2a/push.d.ts.map +1 -0
  26. package/dist/a2a/push.js +180 -0
  27. package/dist/a2a/push.js.map +1 -0
  28. package/dist/a2a/remote.d.ts +155 -0
  29. package/dist/a2a/remote.d.ts.map +1 -0
  30. package/dist/a2a/remote.js +1196 -0
  31. package/dist/a2a/remote.js.map +1 -0
  32. package/dist/a2a/server.d.ts +110 -0
  33. package/dist/a2a/server.d.ts.map +1 -0
  34. package/dist/a2a/server.js +1139 -0
  35. package/dist/a2a/server.js.map +1 -0
  36. package/dist/a2a/signing.d.ts +21 -0
  37. package/dist/a2a/signing.d.ts.map +1 -0
  38. package/dist/a2a/signing.js +305 -0
  39. package/dist/a2a/signing.js.map +1 -0
  40. package/dist/a2a/tasks.d.ts +88 -0
  41. package/dist/a2a/tasks.d.ts.map +1 -0
  42. package/dist/a2a/tasks.js +170 -0
  43. package/dist/a2a/tasks.js.map +1 -0
  44. package/dist/a2a/wire.d.ts +267 -0
  45. package/dist/a2a/wire.d.ts.map +1 -0
  46. package/dist/a2a/wire.js +1202 -0
  47. package/dist/a2a/wire.js.map +1 -0
  48. package/dist/background-types.d.ts +76 -0
  49. package/dist/background-types.d.ts.map +1 -0
  50. package/dist/background-types.js +2 -0
  51. package/dist/background-types.js.map +1 -0
  52. package/dist/child.d.ts +25 -0
  53. package/dist/child.d.ts.map +1 -0
  54. package/dist/child.js +129 -0
  55. package/dist/child.js.map +1 -0
  56. package/dist/code-driver.d.ts +40 -0
  57. package/dist/code-driver.d.ts.map +1 -0
  58. package/dist/code-driver.js +2 -0
  59. package/dist/code-driver.js.map +1 -0
  60. package/dist/code-mode.d.ts +3 -0
  61. package/dist/code-mode.d.ts.map +1 -0
  62. package/dist/code-mode.js +2 -0
  63. package/dist/code-mode.js.map +1 -0
  64. package/dist/code-script.d.ts +3 -0
  65. package/dist/code-script.d.ts.map +1 -0
  66. package/dist/code-script.js +149 -0
  67. package/dist/code-script.js.map +1 -0
  68. package/dist/code.d.ts +75 -0
  69. package/dist/code.d.ts.map +1 -0
  70. package/dist/code.js +326 -0
  71. package/dist/code.js.map +1 -0
  72. package/dist/compaction.d.ts +15 -0
  73. package/dist/compaction.d.ts.map +1 -0
  74. package/dist/compaction.js +168 -0
  75. package/dist/compaction.js.map +1 -0
  76. package/dist/delegation.d.ts +85 -16
  77. package/dist/delegation.d.ts.map +1 -1
  78. package/dist/delegation.js +240 -106
  79. package/dist/delegation.js.map +1 -1
  80. package/dist/evals/driver.d.ts +10 -0
  81. package/dist/evals/driver.d.ts.map +1 -0
  82. package/dist/evals/driver.js +192 -0
  83. package/dist/evals/driver.js.map +1 -0
  84. package/dist/evals/journal.d.ts +26 -0
  85. package/dist/evals/journal.d.ts.map +1 -0
  86. package/dist/evals/journal.js +483 -0
  87. package/dist/evals/journal.js.map +1 -0
  88. package/dist/evals/judge.d.ts +31 -0
  89. package/dist/evals/judge.d.ts.map +1 -0
  90. package/dist/evals/judge.js +142 -0
  91. package/dist/evals/judge.js.map +1 -0
  92. package/dist/evals/report.d.ts +38 -0
  93. package/dist/evals/report.d.ts.map +1 -0
  94. package/dist/evals/report.js +241 -0
  95. package/dist/evals/report.js.map +1 -0
  96. package/dist/evals/runner.d.ts +24 -0
  97. package/dist/evals/runner.d.ts.map +1 -0
  98. package/dist/evals/runner.js +655 -0
  99. package/dist/evals/runner.js.map +1 -0
  100. package/dist/evals/scorers.d.ts +36 -0
  101. package/dist/evals/scorers.d.ts.map +1 -0
  102. package/dist/evals/scorers.js +259 -0
  103. package/dist/evals/scorers.js.map +1 -0
  104. package/dist/evals/simulation.d.ts +7 -0
  105. package/dist/evals/simulation.d.ts.map +1 -0
  106. package/dist/evals/simulation.js +38 -0
  107. package/dist/evals/simulation.js.map +1 -0
  108. package/dist/evals/testing.d.ts +36 -0
  109. package/dist/evals/testing.d.ts.map +1 -0
  110. package/dist/evals/testing.js +87 -0
  111. package/dist/evals/testing.js.map +1 -0
  112. package/dist/evals/trajectory.d.ts +11 -0
  113. package/dist/evals/trajectory.d.ts.map +1 -0
  114. package/dist/evals/trajectory.js +180 -0
  115. package/dist/evals/trajectory.js.map +1 -0
  116. package/dist/evals/types.d.ts +431 -0
  117. package/dist/evals/types.d.ts.map +1 -0
  118. package/dist/evals/types.js +4 -0
  119. package/dist/evals/types.js.map +1 -0
  120. package/dist/evals.d.ts +14 -0
  121. package/dist/evals.d.ts.map +1 -0
  122. package/dist/evals.js +9 -0
  123. package/dist/evals.js.map +1 -0
  124. package/dist/extensions.d.ts +33 -0
  125. package/dist/extensions.d.ts.map +1 -0
  126. package/dist/extensions.js +188 -0
  127. package/dist/extensions.js.map +1 -0
  128. package/dist/handoff.d.ts +58 -0
  129. package/dist/handoff.d.ts.map +1 -0
  130. package/dist/handoff.js +160 -0
  131. package/dist/handoff.js.map +1 -0
  132. package/dist/index.d.ts +14 -0
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js +8 -0
  135. package/dist/index.js.map +1 -1
  136. package/dist/input.d.ts +42 -0
  137. package/dist/input.d.ts.map +1 -0
  138. package/dist/input.js +266 -0
  139. package/dist/input.js.map +1 -0
  140. package/dist/mcp.d.ts +77 -0
  141. package/dist/mcp.d.ts.map +1 -0
  142. package/dist/mcp.js +505 -0
  143. package/dist/mcp.js.map +1 -0
  144. package/dist/memory-store.d.ts +11 -0
  145. package/dist/memory-store.d.ts.map +1 -0
  146. package/dist/memory-store.js +272 -0
  147. package/dist/memory-store.js.map +1 -0
  148. package/dist/memory.d.ts +212 -0
  149. package/dist/memory.d.ts.map +1 -0
  150. package/dist/memory.js +613 -0
  151. package/dist/memory.js.map +1 -0
  152. package/dist/otel.d.ts +74 -0
  153. package/dist/otel.d.ts.map +1 -0
  154. package/dist/otel.js +427 -0
  155. package/dist/otel.js.map +1 -0
  156. package/dist/progress.d.ts +17 -0
  157. package/dist/progress.d.ts.map +1 -0
  158. package/dist/progress.js +193 -0
  159. package/dist/progress.js.map +1 -0
  160. package/dist/quickjs.d.ts +19 -0
  161. package/dist/quickjs.d.ts.map +1 -0
  162. package/dist/quickjs.js +519 -0
  163. package/dist/quickjs.js.map +1 -0
  164. package/dist/recovery.d.ts +10 -0
  165. package/dist/recovery.d.ts.map +1 -0
  166. package/dist/recovery.js +62 -0
  167. package/dist/recovery.js.map +1 -0
  168. package/dist/request.d.ts +88 -0
  169. package/dist/request.d.ts.map +1 -0
  170. package/dist/request.js +422 -0
  171. package/dist/request.js.map +1 -0
  172. package/dist/run.d.ts +16 -4
  173. package/dist/run.d.ts.map +1 -1
  174. package/dist/run.js +2016 -245
  175. package/dist/run.js.map +1 -1
  176. package/dist/runs.d.ts +77 -34
  177. package/dist/runs.d.ts.map +1 -1
  178. package/dist/runs.js +267 -85
  179. package/dist/runs.js.map +1 -1
  180. package/dist/schema-to-ts.d.ts +4 -0
  181. package/dist/schema-to-ts.d.ts.map +1 -0
  182. package/dist/schema-to-ts.js +191 -0
  183. package/dist/schema-to-ts.js.map +1 -0
  184. package/dist/session.d.ts +23 -0
  185. package/dist/session.d.ts.map +1 -0
  186. package/dist/session.js +137 -0
  187. package/dist/session.js.map +1 -0
  188. package/dist/snapshot.d.ts +57 -8
  189. package/dist/snapshot.d.ts.map +1 -1
  190. package/dist/snapshot.js +1206 -109
  191. package/dist/snapshot.js.map +1 -1
  192. package/dist/steering.d.ts +75 -0
  193. package/dist/steering.d.ts.map +1 -0
  194. package/dist/steering.js +214 -0
  195. package/dist/steering.js.map +1 -0
  196. package/dist/subagents.d.ts +141 -0
  197. package/dist/subagents.d.ts.map +1 -0
  198. package/dist/subagents.js +746 -0
  199. package/dist/subagents.js.map +1 -0
  200. package/dist/tool-retry.d.ts +12 -0
  201. package/dist/tool-retry.d.ts.map +1 -0
  202. package/dist/tool-retry.js +53 -0
  203. package/dist/tool-retry.js.map +1 -0
  204. package/dist/tree.d.ts +62 -6
  205. package/dist/tree.d.ts.map +1 -1
  206. package/dist/tree.js +192 -23
  207. package/dist/tree.js.map +1 -1
  208. package/dist/types.d.ts +767 -52
  209. package/dist/types.d.ts.map +1 -1
  210. package/dist/workflow-snapshot.d.ts +8 -0
  211. package/dist/workflow-snapshot.d.ts.map +1 -0
  212. package/dist/workflow-snapshot.js +276 -0
  213. package/dist/workflow-snapshot.js.map +1 -0
  214. package/dist/workflow-types.d.ts +171 -0
  215. package/dist/workflow-types.d.ts.map +1 -0
  216. package/dist/workflow-types.js +2 -0
  217. package/dist/workflow-types.js.map +1 -0
  218. package/dist/workflow.d.ts +19 -0
  219. package/dist/workflow.d.ts.map +1 -0
  220. package/dist/workflow.js +1053 -0
  221. package/dist/workflow.js.map +1 -0
  222. package/examples/a2a-remote.ts +85 -0
  223. package/examples/a2a-server.ts +100 -0
  224. package/examples/background.ts +18 -4
  225. package/examples/code-mode.ts +76 -0
  226. package/examples/conversation.ts +57 -0
  227. package/examples/evals.ts +79 -0
  228. package/examples/guardrails.ts +56 -0
  229. package/examples/handoff.ts +79 -0
  230. package/examples/memory.ts +44 -0
  231. package/examples/otel.ts +99 -0
  232. package/examples/steering.ts +69 -0
  233. package/examples/structured-handoff.ts +92 -0
  234. package/examples/subagents.ts +127 -0
  235. package/examples/workflow.ts +74 -0
  236. package/package.json +58 -6
  237. package/src/a2a/auth.ts +62 -0
  238. package/src/a2a/client.ts +733 -0
  239. package/src/a2a/index.ts +74 -0
  240. package/src/a2a/memory-runs.ts +448 -0
  241. package/src/a2a/policy.ts +148 -0
  242. package/src/a2a/push.ts +251 -0
  243. package/src/a2a/remote.ts +1652 -0
  244. package/src/a2a/server.ts +1390 -0
  245. package/src/a2a/signing.ts +348 -0
  246. package/src/a2a/tasks.ts +260 -0
  247. package/src/a2a/wire.ts +1443 -0
  248. package/src/background-types.ts +86 -0
  249. package/src/child.ts +181 -0
  250. package/src/code-driver.ts +48 -0
  251. package/src/code-mode.ts +12 -0
  252. package/src/code-script.ts +149 -0
  253. package/src/code.ts +424 -0
  254. package/src/compaction.ts +212 -0
  255. package/src/delegation.ts +444 -155
  256. package/src/evals/driver.ts +222 -0
  257. package/src/evals/journal.ts +605 -0
  258. package/src/evals/judge.ts +188 -0
  259. package/src/evals/report.ts +295 -0
  260. package/src/evals/runner.ts +826 -0
  261. package/src/evals/scorers.ts +339 -0
  262. package/src/evals/simulation.ts +46 -0
  263. package/src/evals/testing.ts +126 -0
  264. package/src/evals/trajectory.ts +223 -0
  265. package/src/evals/types.ts +463 -0
  266. package/src/evals.ts +72 -0
  267. package/src/extensions.ts +247 -0
  268. package/src/handoff.ts +214 -0
  269. package/src/index.ts +51 -0
  270. package/src/input.ts +319 -0
  271. package/src/mcp.ts +690 -0
  272. package/src/memory-store.ts +366 -0
  273. package/src/memory.ts +893 -0
  274. package/src/otel.ts +568 -0
  275. package/src/progress.ts +214 -0
  276. package/src/quickjs.ts +524 -0
  277. package/src/recovery.ts +90 -0
  278. package/src/request.ts +513 -0
  279. package/src/run.ts +2678 -313
  280. package/src/runs.ts +464 -133
  281. package/src/schema-to-ts.ts +194 -0
  282. package/src/session.ts +178 -0
  283. package/src/snapshot.ts +1595 -124
  284. package/src/steering.ts +329 -0
  285. package/src/subagents.ts +1084 -0
  286. package/src/tool-retry.ts +86 -0
  287. package/src/tree.ts +223 -27
  288. package/src/types.ts +711 -52
  289. package/src/workflow-snapshot.ts +366 -0
  290. package/src/workflow-types.ts +213 -0
  291. package/src/workflow.ts +1316 -0
@@ -0,0 +1,348 @@
1
+ // Card-signing design adapted from Mastra's agent-card-signing.ts (Apache-2.0).
2
+ // Copyright (c) 2025 Kepler Software, Inc. JCS: RFC 8785; detached JWS: RFC 7515.
3
+ import { A2AError, parseA2AJson, type A2AAgentCard, type A2AJson, type A2AObject } from "./wire.ts";
4
+
5
+ export interface A2ACardSigner {
6
+ key: CryptoKey;
7
+ kid: string;
8
+ alg: "ES256" | "EdDSA" | "RS256";
9
+ }
10
+ const encoder = new TextEncoder();
11
+
12
+ /** JCS sorts UTF-16 keys and uses ECMAScript number formatting. Reject non-JSON values and
13
+ * lone surrogates instead of signing a lossy serialization. Also used for message identity. */
14
+ export function canonicalA2AJson(value: A2AJson): string {
15
+ if (typeof value === "string") {
16
+ if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value))
17
+ throw new A2AError("invalid");
18
+ return JSON.stringify(value);
19
+ }
20
+ if (value === null || typeof value === "boolean") return JSON.stringify(value);
21
+ if (typeof value === "number") {
22
+ if (!Number.isFinite(value)) throw new A2AError("invalid");
23
+ return JSON.stringify(value);
24
+ }
25
+ if (Array.isArray(value)) return `[${value.map(canonicalA2AJson).join(",")}]`;
26
+ if (
27
+ !value ||
28
+ (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
29
+ )
30
+ throw new A2AError("invalid");
31
+ return `{${Object.keys(value)
32
+ .sort()
33
+ .map((key) => `${canonicalA2AJson(key)}:${canonicalA2AJson(value[key]!)}`)
34
+ .join(",")}}`;
35
+ }
36
+ /** Stores content identity without retaining another copy of a message or credential. */
37
+ export async function hashA2AJson(value: A2AJson): Promise<string> {
38
+ const digest = await crypto.subtle.digest("SHA-256", encoder.encode(canonicalA2AJson(value)));
39
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
40
+ }
41
+ function encode(bytes: Uint8Array): string {
42
+ let text = "";
43
+ for (const byte of bytes) text += String.fromCharCode(byte);
44
+ return btoa(text).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
45
+ }
46
+ function decode(text: string): Uint8Array<ArrayBuffer> {
47
+ if (!/^[A-Za-z0-9_-]+$/.test(text) || text.length % 4 === 1) throw new A2AError("invalid");
48
+ const bytes = Uint8Array.from(atob(text.replaceAll("-", "+").replaceAll("_", "/")), (c) =>
49
+ c.charCodeAt(0),
50
+ );
51
+ if (encode(bytes) !== text) throw new A2AError("invalid");
52
+ return bytes;
53
+ }
54
+ function algorithm(
55
+ alg: string,
56
+ key: CryptoKey,
57
+ usage: "sign" | "verify",
58
+ ): AlgorithmIdentifier | EcdsaParams {
59
+ if (key.type !== (usage === "sign" ? "private" : "public") || !key.usages.includes(usage))
60
+ throw new A2AError("invalid");
61
+ if (
62
+ alg === "ES256" &&
63
+ key.algorithm.name === "ECDSA" &&
64
+ "namedCurve" in key.algorithm &&
65
+ key.algorithm.namedCurve === "P-256"
66
+ )
67
+ return { name: "ECDSA", hash: "SHA-256" };
68
+ if (alg === "EdDSA" && key.algorithm.name === "Ed25519") return "Ed25519";
69
+ if (alg === "RS256" && key.algorithm.name === "RSASSA-PKCS1-v1_5" && "hash" in key.algorithm) {
70
+ const hash = key.algorithm.hash;
71
+ if (hash && typeof hash === "object" && "name" in hash && hash.name === "SHA-256")
72
+ return "RSASSA-PKCS1-v1_5";
73
+ }
74
+ throw new A2AError("invalid");
75
+ }
76
+ // A2A 1.0 §8.4.1 normalizes protobuf fields BEFORE JCS, unlike 0.3's raw-card JCS.
77
+ // Field list: a2aproject/A2A v1.0.0 a2a.proto. Empty-value removal matched against
78
+ // a2a-js 1.3.0 src/signature.ts (Apache-2.0).
79
+ function object(value: A2AJson | undefined): A2AObject {
80
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new A2AError("invalid");
81
+ return value;
82
+ }
83
+ function fields(value: A2AJson, names: string[]): A2AObject {
84
+ const source = object(value);
85
+ return Object.fromEntries(
86
+ names
87
+ .filter((name) => source[name] !== undefined && source[name] !== null)
88
+ .map((name) => {
89
+ if (typeof source[name] !== "string") throw new A2AError("invalid");
90
+ return [name, source[name]!];
91
+ }),
92
+ );
93
+ }
94
+ function array(value: A2AJson, map: (entry: A2AJson) => A2AJson): A2AJson[] {
95
+ if (!Array.isArray(value)) throw new A2AError("invalid");
96
+ return value.map(map);
97
+ }
98
+ function strings(value: A2AJson): A2AJson[] {
99
+ return array(value, (entry) => {
100
+ if (typeof entry !== "string") throw new A2AError("invalid");
101
+ return entry;
102
+ });
103
+ }
104
+ function mapping(value: A2AJson, map: (entry: A2AJson) => A2AJson): A2AObject {
105
+ return Object.fromEntries(Object.entries(object(value)).map(([key, entry]) => [key, map(entry)]));
106
+ }
107
+ function present(
108
+ source: A2AObject,
109
+ target: A2AObject,
110
+ key: string,
111
+ map: (v: A2AJson) => A2AJson,
112
+ ): void {
113
+ if (source[key] !== undefined && source[key] !== null) target[key] = map(source[key]);
114
+ }
115
+ function boolean(value: A2AJson): boolean {
116
+ if (typeof value !== "boolean") throw new A2AError("invalid");
117
+ return value;
118
+ }
119
+ function requirements(value: A2AJson): A2AJson[] {
120
+ return array(value, (entry) => {
121
+ const result: A2AObject = {};
122
+ present(object(entry), result, "schemes", (schemes) =>
123
+ mapping(schemes, (scope) => {
124
+ const list: A2AObject = {};
125
+ present(object(scope), list, "list", strings);
126
+ return list;
127
+ }),
128
+ );
129
+ return result;
130
+ });
131
+ }
132
+ function flow(value: A2AJson, name: string): A2AObject {
133
+ const names =
134
+ name === "authorizationCode"
135
+ ? ["authorizationUrl", "tokenUrl", "refreshUrl"]
136
+ : name === "implicit"
137
+ ? ["authorizationUrl", "refreshUrl"]
138
+ : name === "deviceCode"
139
+ ? ["deviceAuthorizationUrl", "tokenUrl", "refreshUrl"]
140
+ : ["tokenUrl", "refreshUrl"];
141
+ const result = fields(value, names);
142
+ const source = object(value);
143
+ present(source, result, "scopes", (scopes) =>
144
+ mapping(scopes, (scope) => {
145
+ if (typeof scope !== "string") throw new A2AError("invalid");
146
+ return scope;
147
+ }),
148
+ );
149
+ if (
150
+ name === "authorizationCode" &&
151
+ source.pkceRequired !== undefined &&
152
+ boolean(source.pkceRequired)
153
+ )
154
+ result.pkceRequired = true;
155
+ return result;
156
+ }
157
+ function security(value: A2AJson): A2AObject {
158
+ const source = object(value);
159
+ const variants = [
160
+ "apiKeySecurityScheme",
161
+ "httpAuthSecurityScheme",
162
+ "oauth2SecurityScheme",
163
+ "openIdConnectSecurityScheme",
164
+ "mtlsSecurityScheme",
165
+ ].filter((key) => source[key] !== undefined && source[key] !== null);
166
+ if (variants.length > 1) throw new A2AError("invalid");
167
+ if (!variants.length) return {};
168
+ const key = variants[0]!;
169
+ const scheme = object(source[key]);
170
+ const names =
171
+ key === "apiKeySecurityScheme"
172
+ ? ["description", "location", "name"]
173
+ : key === "httpAuthSecurityScheme"
174
+ ? ["description", "scheme", "bearerFormat"]
175
+ : key === "oauth2SecurityScheme"
176
+ ? ["description", "oauth2MetadataUrl"]
177
+ : key === "openIdConnectSecurityScheme"
178
+ ? ["description", "openIdConnectUrl"]
179
+ : ["description"];
180
+ const result = fields(scheme, names);
181
+ if (key === "oauth2SecurityScheme")
182
+ present(scheme, result, "flows", (value) => {
183
+ const source = object(value);
184
+ const keys = [
185
+ "authorizationCode",
186
+ "clientCredentials",
187
+ "implicit",
188
+ "password",
189
+ "deviceCode",
190
+ ].filter((name) => source[name] !== undefined && source[name] !== null);
191
+ if (keys.length > 1) throw new A2AError("invalid");
192
+ return Object.fromEntries(keys.map((name) => [name, flow(source[name]!, name)]));
193
+ });
194
+ return { [key]: result };
195
+ }
196
+ function cleanEmpty(value: A2AJson): A2AJson | undefined {
197
+ if (value === "" || value === null) return undefined;
198
+ if (Array.isArray(value)) {
199
+ const result = value.map(cleanEmpty).filter((entry): entry is A2AJson => entry !== undefined);
200
+ return result.length ? result : undefined;
201
+ }
202
+ if (typeof value === "object") {
203
+ const entries = Object.entries(value).flatMap(([key, entry]) => {
204
+ const cleaned = cleanEmpty(entry);
205
+ return cleaned === undefined ? [] : [[key, cleaned]];
206
+ });
207
+ return entries.length ? Object.fromEntries(entries) : undefined;
208
+ }
209
+ return value;
210
+ }
211
+ /** 1.0 signatures cover only schema fields after protobuf normalization. Unknown fields and
212
+ * empty extension values are NOT authenticated. Do not use them as permission or trust data. */
213
+ export function canonicalA2ACard(card: A2AAgentCard): string {
214
+ const { signatures: _signatures, ...document } = card.document;
215
+ // Validate Unicode even in fields normalization later drops.
216
+ canonicalA2AJson(document);
217
+ if (card.version === "0.3") return canonicalA2AJson(document);
218
+ const result = fields(document, [
219
+ "name",
220
+ "description",
221
+ "version",
222
+ "documentationUrl",
223
+ "iconUrl",
224
+ ]);
225
+ present(document, result, "supportedInterfaces", (v) =>
226
+ array(v, (entry) => fields(entry, ["url", "protocolBinding", "protocolVersion", "tenant"])),
227
+ );
228
+ present(document, result, "provider", (v) => fields(v, ["url", "organization"]));
229
+ present(document, result, "capabilities", (v) => {
230
+ const source = object(v);
231
+ const capabilities: A2AObject = {};
232
+ for (const key of ["streaming", "pushNotifications", "extendedAgentCard"])
233
+ present(source, capabilities, key, boolean);
234
+ present(source, capabilities, "extensions", (v) =>
235
+ array(v, (entry) => {
236
+ const extension = fields(entry, ["uri", "description"]);
237
+ const original = object(entry);
238
+ if (original.required !== undefined && boolean(original.required))
239
+ extension.required = true;
240
+ present(original, extension, "params", object);
241
+ return extension;
242
+ }),
243
+ );
244
+ return capabilities;
245
+ });
246
+ present(document, result, "securitySchemes", (v) => mapping(v, security));
247
+ present(document, result, "securityRequirements", requirements);
248
+ for (const key of ["defaultInputModes", "defaultOutputModes"])
249
+ present(document, result, key, strings);
250
+ present(document, result, "skills", (v) =>
251
+ array(v, (entry) => {
252
+ const skill = fields(entry, ["id", "name", "description"]);
253
+ const source = object(entry);
254
+ for (const key of ["tags", "examples", "inputModes", "outputModes"])
255
+ present(source, skill, key, strings);
256
+ present(source, skill, "securityRequirements", requirements);
257
+ return skill;
258
+ }),
259
+ );
260
+ return canonicalA2AJson(cleanEmpty(result) ?? {});
261
+ }
262
+ function payload(card: A2AAgentCard): string {
263
+ return encode(encoder.encode(canonicalA2ACard(card)));
264
+ }
265
+
266
+ /** Signs the version's canonical public document. Sign each version separately. Possession
267
+ * of a signing key does not authorize task access or tool execution. */
268
+ export async function signAgentCard(
269
+ card: A2AAgentCard,
270
+ signer: A2ACardSigner,
271
+ ): Promise<A2AAgentCard> {
272
+ if (!signer.kid || signer.kid.length > 512) throw new A2AError("invalid");
273
+ const copy = structuredClone(card);
274
+ const protectedHeader = encode(
275
+ encoder.encode(canonicalA2AJson({ alg: signer.alg, kid: signer.kid, typ: "JOSE" })),
276
+ );
277
+ const signature = await crypto.subtle.sign(
278
+ algorithm(signer.alg, signer.key, "sign"),
279
+ signer.key,
280
+ encoder.encode(`${protectedHeader}.${payload(copy)}`),
281
+ );
282
+ copy.document.signatures = [
283
+ { protected: protectedHeader, signature: encode(new Uint8Array(signature)) },
284
+ ];
285
+ return copy;
286
+ }
287
+
288
+ /** Keys are pinned by the host. Never follows jku/x5u or trusts a key embedded in a card.
289
+ * True means one pinned signature is valid, not that the signer has any application permission. */
290
+ export async function verifyAgentCard(
291
+ card: A2AAgentCard,
292
+ keys: Readonly<Record<string, CryptoKey>>,
293
+ ): Promise<boolean> {
294
+ try {
295
+ const signatures = card.document.signatures;
296
+ if (!Array.isArray(signatures) || !signatures.length || signatures.length > 16) return false;
297
+ const encoded = payload(card);
298
+ for (const signature of signatures) {
299
+ if (
300
+ !signature ||
301
+ typeof signature !== "object" ||
302
+ Array.isArray(signature) ||
303
+ typeof signature.protected !== "string" ||
304
+ typeof signature.signature !== "string"
305
+ )
306
+ continue;
307
+ try {
308
+ const header = parseA2AJson(
309
+ new TextDecoder("utf-8", { fatal: true }).decode(decode(signature.protected)),
310
+ { bodyBytes: 8192 },
311
+ );
312
+ if (
313
+ !header ||
314
+ typeof header !== "object" ||
315
+ Array.isArray(header) ||
316
+ typeof header.kid !== "string" ||
317
+ typeof header.alg !== "string" ||
318
+ (card.version === "1.0" && (typeof header.typ !== "string" || !header.typ)) ||
319
+ !Object.hasOwn(keys, header.kid)
320
+ )
321
+ continue;
322
+ // No unencoded payloads or critical extensions. Key discovery is deliberately absent.
323
+ if (Object.keys(header).some((key) => !["alg", "kid", "typ"].includes(key))) continue;
324
+ if (
325
+ signature.header &&
326
+ typeof signature.header === "object" &&
327
+ Object.keys(signature.header).some((key) => Object.hasOwn(header, key))
328
+ )
329
+ continue;
330
+ const key = keys[header.kid]!;
331
+ if (
332
+ await crypto.subtle.verify(
333
+ algorithm(header.alg, key, "verify"),
334
+ key,
335
+ decode(signature.signature),
336
+ encoder.encode(`${signature.protected}.${encoded}`),
337
+ )
338
+ )
339
+ return true;
340
+ } catch {
341
+ /* An unsupported or invalid signature cannot establish trust. */
342
+ }
343
+ }
344
+ } catch {
345
+ /* Refuse malformed canonical JSON without retaining peer content. */
346
+ }
347
+ return false;
348
+ }
@@ -0,0 +1,260 @@
1
+ // Owner partitioning follows Microsoft's IsolationKeyScopedTaskStore (MIT).
2
+ // Copyright (c) Microsoft Corporation. Message claims and bounded retention are providerkit's.
3
+ import { equalData } from "../snapshot.ts";
4
+ import type { SegmentHook } from "../background-types.ts";
5
+ import type { A2APrincipal } from "./auth.ts";
6
+ import {
7
+ A2AError,
8
+ type A2ADialect,
9
+ type A2AMessage,
10
+ type A2APushConfig,
11
+ type A2AState,
12
+ } from "./wire.ts";
13
+
14
+ /** Tenant is selected by trusted host configuration, not by a request's tenant field. */
15
+ export interface A2ATaskScope extends A2APrincipal {
16
+ tenant?: string;
17
+ }
18
+ export interface A2AMessageReceipt {
19
+ id: string;
20
+ fingerprint: string;
21
+ kind: "start" | "resume" | "steer";
22
+ /** pending is already a reservation: never repeat the effect, even after a lost reply. */
23
+ acceptance: "pending" | "accepted" | "unknown";
24
+ segment?: string;
25
+ source?: string;
26
+ /** Exact evidence reserved before resume. Private, never projected as A2A history. */
27
+ answers?: Readonly<Record<string, unknown>>;
28
+ }
29
+ export interface A2APushRecord {
30
+ config: A2APushConfig;
31
+ dialect: A2ADialect;
32
+ }
33
+ export interface A2APushAttempt {
34
+ id: string;
35
+ configId: string;
36
+ revision: string;
37
+ at: number;
38
+ outcome: "pending" | "delivered" | "refused" | "unknown";
39
+ }
40
+ export interface A2ATaskRecord extends A2ATaskScope {
41
+ id: string;
42
+ contextId: string;
43
+ hops: number;
44
+ segment?: string;
45
+ state: A2AState;
46
+ messages: A2AMessageReceipt[];
47
+ /** Only peer messages and explicitly projected public messages, never the run journal. */
48
+ history: A2AMessage[];
49
+ push: A2APushRecord[];
50
+ deliveries: A2APushAttempt[];
51
+ cancel?: "pending" | "accepted" | "unknown" | "refused";
52
+ createdAt: number;
53
+ updatedAt: number;
54
+ revision: string;
55
+ }
56
+ export type A2ATaskPatch = Partial<
57
+ Pick<
58
+ A2ATaskRecord,
59
+ "segment" | "state" | "messages" | "history" | "push" | "deliveries" | "cancel"
60
+ >
61
+ >;
62
+ export interface A2ATaskStore {
63
+ /** Atomic on both (scope,id) and (scope,messageId). Changed duplicate content must throw. */
64
+ create(record: A2ATaskRecord): Promise<{ created: boolean; record: A2ATaskRecord }>;
65
+ get(scope: A2ATaskScope, id: string): Promise<A2ATaskRecord | null>;
66
+ findMessage(scope: A2ATaskScope, id: string): Promise<A2ATaskRecord | null>;
67
+ /** CAS also claims every newly added messageId across the scope. No writes on conflict. */
68
+ update(
69
+ scope: A2ATaskScope,
70
+ id: string,
71
+ patch: A2ATaskPatch,
72
+ revision: string,
73
+ ): Promise<A2ATaskRecord>;
74
+ list(
75
+ scope: A2ATaskScope,
76
+ filter: { contextId?: string; pageSize: number; pageToken?: string },
77
+ ): Promise<{ tasks: A2ATaskRecord[]; nextPageToken: string }>;
78
+ hasContext(scope: A2ATaskScope, contextId: string): Promise<boolean>;
79
+ }
80
+ export class A2ATaskConflict extends A2AError {
81
+ constructor() {
82
+ super("invalid", { code: -32602 });
83
+ }
84
+ }
85
+ export function a2aTerminal(state: A2AState): boolean {
86
+ return ["completed", "failed", "canceled", "rejected"].includes(state);
87
+ }
88
+ export function taskScope(record: A2ATaskScope): A2ATaskScope {
89
+ return {
90
+ owner: record.owner,
91
+ actorId: record.actorId,
92
+ ...(record.tenant ? { tenant: record.tenant } : {}),
93
+ };
94
+ }
95
+ function scopeKey(scope: A2ATaskScope): string {
96
+ if (!scope.owner || !scope.actorId) throw new A2AError("invalid");
97
+ return JSON.stringify([scope.owner, scope.actorId, scope.tenant ?? null]);
98
+ }
99
+
100
+ /** Process-local, not crash durable. Full stores refuse additional data, never evict dedupe
101
+ * receipts. Discarding this store also discards its no-replay window. Hosts own retention.
102
+ * ponytail: context/list queries scan at most maxTasks (1,000 by default). Use an indexed host
103
+ * store when that bounded scan is too large; this reference store is not a database. */
104
+ export function createMemoryTaskStore(
105
+ options: { maxTasks?: number; maxRecordBytes?: number; maxMessages?: number } = {},
106
+ ): A2ATaskStore {
107
+ const { maxTasks = 1000, maxRecordBytes = 1024 * 1024, maxMessages = 256 } = options;
108
+ if ([maxTasks, maxRecordBytes, maxMessages].some((n) => !Number.isSafeInteger(n) || n < 1))
109
+ throw new A2AError("invalid");
110
+ const records = new Map<string, A2ATaskRecord>();
111
+ const messages = new Map<string, string>();
112
+ const key = (scope: A2ATaskScope, id: string) => JSON.stringify([scopeKey(scope), id]);
113
+ function save(record: A2ATaskRecord) {
114
+ if (
115
+ record.messages.length > maxMessages ||
116
+ record.history.length > 100 ||
117
+ record.push.length > 10 ||
118
+ record.deliveries.length > 256 ||
119
+ new TextEncoder().encode(JSON.stringify(record)).byteLength > maxRecordBytes
120
+ )
121
+ throw new A2AError("limit");
122
+ const seen = new Set<string>();
123
+ for (const message of record.messages) {
124
+ const existing = messages.get(key(record, message.id));
125
+ if (seen.has(message.id) || (existing && existing !== record.id)) throw new A2ATaskConflict();
126
+ seen.add(message.id);
127
+ }
128
+ records.set(key(record, record.id), structuredClone(record));
129
+ for (const message of record.messages) messages.set(key(record, message.id), record.id);
130
+ return structuredClone(record);
131
+ }
132
+ return {
133
+ async create(record) {
134
+ if (record.messages.length !== 1 || record.messages[0]?.kind !== "start")
135
+ throw new A2AError("invalid");
136
+ const receipt = record.messages[0];
137
+ const existingId = messages.get(key(record, receipt.id));
138
+ const existing = records.get(key(record, existingId ?? record.id));
139
+ if (existing) {
140
+ const old = existing.messages.find((m) => m.id === receipt.id);
141
+ if (!old || old.fingerprint !== receipt.fingerprint) throw new A2ATaskConflict();
142
+ return { created: false, record: structuredClone(existing) };
143
+ }
144
+ if (records.size >= maxTasks) throw new A2AError("limit");
145
+ return { created: true, record: save({ ...record, revision: crypto.randomUUID() }) };
146
+ },
147
+ async get(scope, id) {
148
+ return structuredClone(records.get(key(scope, id)) ?? null);
149
+ },
150
+ async findMessage(scope, id) {
151
+ const taskId = messages.get(key(scope, id));
152
+ return structuredClone(taskId ? (records.get(key(scope, taskId)) ?? null) : null);
153
+ },
154
+ async update(scope, id, patch, revision) {
155
+ const old = records.get(key(scope, id));
156
+ if (!old) throw new A2AError("protocol", { code: -32001 });
157
+ if (old.revision !== revision) throw new A2ATaskConflict();
158
+ if (
159
+ Object.keys(patch).some(
160
+ (field) =>
161
+ !["segment", "state", "messages", "history", "push", "deliveries", "cancel"].includes(
162
+ field,
163
+ ),
164
+ )
165
+ )
166
+ throw new A2AError("invalid");
167
+ if (patch.messages) {
168
+ for (const [index, receipt] of old.messages.entries()) {
169
+ const next = patch.messages[index];
170
+ if (
171
+ !next ||
172
+ next.id !== receipt.id ||
173
+ next.fingerprint !== receipt.fingerprint ||
174
+ next.kind !== receipt.kind ||
175
+ next.source !== receipt.source ||
176
+ !equalData(next.answers, receipt.answers) ||
177
+ (receipt.acceptance === "unknown" && next.acceptance === "pending") ||
178
+ (receipt.acceptance === "accepted" && !equalData(next, receipt))
179
+ )
180
+ throw new A2ATaskConflict();
181
+ }
182
+ }
183
+ if (a2aTerminal(old.state) && patch.state && patch.state !== old.state)
184
+ throw new A2ATaskConflict();
185
+ const changed =
186
+ (patch.state !== undefined && patch.state !== old.state) ||
187
+ (patch.segment !== undefined && patch.segment !== old.segment) ||
188
+ (patch.history !== undefined && !equalData(patch.history, old.history));
189
+ return save({
190
+ ...old,
191
+ ...structuredClone(patch),
192
+ revision: crypto.randomUUID(),
193
+ updatedAt: changed ? Date.now() : old.updatedAt,
194
+ });
195
+ },
196
+ async list(scope, filter) {
197
+ if (!Number.isSafeInteger(filter.pageSize) || filter.pageSize < 1 || filter.pageSize > 100)
198
+ throw new A2AError("invalid");
199
+ const prefix = scopeKey(scope);
200
+ const found = [...records.values()].filter(
201
+ (r) => scopeKey(r) === prefix && (!filter.contextId || r.contextId === filter.contextId),
202
+ );
203
+ const index = filter.pageToken ? found.findIndex((r) => r.id === filter.pageToken) + 1 : 0;
204
+ if (filter.pageToken && index === 0) throw new A2AError("invalid");
205
+ const tasks = found.slice(index, index + filter.pageSize);
206
+ return {
207
+ tasks: structuredClone(tasks),
208
+ nextPageToken: index + tasks.length < found.length ? tasks.at(-1)!.id : "",
209
+ };
210
+ },
211
+ async hasContext(scope, id) {
212
+ const prefix = scopeKey(scope);
213
+ return [...records.values()].some((r) => scopeKey(r) === prefix && r.contextId === id);
214
+ },
215
+ };
216
+ }
217
+
218
+ /** Install in every worker. scope must recover the original authenticated partition from host
219
+ * storage. onChange is awaited; an end failure never changes the runtime's completed journal. */
220
+ export function a2aSegments(options: {
221
+ tasks: A2ATaskStore;
222
+ scope(owner: string, runId: string): A2ATaskScope | Promise<A2ATaskScope>;
223
+ onChange?: (record: A2ATaskRecord, segment: Parameters<SegmentHook>[0]) => void | Promise<void>;
224
+ }): SegmentHook {
225
+ return async (segment) => {
226
+ const scope = await options.scope(segment.owner, segment.runId);
227
+ if (scope.owner !== segment.owner) throw new A2AError("invalid");
228
+ for (let attempt = 0; attempt < 4; attempt++) {
229
+ const record = await options.tasks.get(scope, segment.runId);
230
+ if (!record) throw new A2AError("protocol", { code: -32001 });
231
+ if (a2aTerminal(record.state) || (segment.phase === "end" && record.segment !== segment.id))
232
+ return;
233
+ const state: A2AState =
234
+ segment.phase === "start"
235
+ ? "working"
236
+ : segment.state.status === "completed"
237
+ ? "completed"
238
+ : segment.state.status === "cancelled"
239
+ ? "canceled"
240
+ : ["failed", "limited"].includes(segment.state.status)
241
+ ? "failed"
242
+ : "working";
243
+ let updated: A2ATaskRecord;
244
+ try {
245
+ updated = await options.tasks.update(
246
+ scope,
247
+ record.id,
248
+ { segment: segment.id, state },
249
+ record.revision,
250
+ );
251
+ } catch (error) {
252
+ if (!(error instanceof A2ATaskConflict) || attempt === 3) throw error;
253
+ continue;
254
+ }
255
+ // Never retry a host callback: it may have sent a notification before throwing.
256
+ await options.onChange?.(updated, segment);
257
+ return;
258
+ }
259
+ };
260
+ }