@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,1390 @@
1
+ // Fail-closed serving policy follows Google ADK (Apache-2.0, Google LLC).
2
+ // Generic failures/owner scoping follow Microsoft Agent Framework (MIT, Microsoft Corporation).
3
+ // Public cards and version selection follow Mastra (Apache-2.0, Kepler Software, Inc.).
4
+ import { sleep } from "@providerkit/core";
5
+ import type { BackgroundContext, BackgroundPolicy } from "../background-types.ts";
6
+ import type { NodeOutcome } from "../delegation.ts";
7
+ import {
8
+ copyData,
9
+ equalData,
10
+ immutableCopy,
11
+ isRecord,
12
+ isImageMime,
13
+ isFileMime,
14
+ } from "../snapshot.ts";
15
+ import { openRequests, requestRecords, untilAbort } from "../tree.ts";
16
+ import type { AgentInput, InputPart, PendingRequest, RunFailure } from "../types.ts";
17
+ import { authenticateA2A, type A2AAuthenticate, type A2APrincipal } from "./auth.ts";
18
+ import { decodeA2AHttpRequest, readA2AJson } from "./client.ts";
19
+ import type { A2ARun, A2ARuns, A2AStoredEvent } from "./memory-runs.ts";
20
+ import { checkA2APushConfig, deliverA2APush, type A2APushPolicy } from "./push.ts";
21
+ import { canonicalA2AJson, hashA2AJson, signAgentCard, type A2ACardSigner } from "./signing.ts";
22
+ import {
23
+ a2aTerminal,
24
+ A2ATaskConflict,
25
+ taskScope,
26
+ type A2AMessageReceipt,
27
+ type A2ATaskPatch,
28
+ type A2ATaskRecord,
29
+ type A2ATaskScope,
30
+ type A2ATaskStore,
31
+ } from "./tasks.ts";
32
+ import {
33
+ A2AError,
34
+ a2aLimits,
35
+ a2aStateClosed,
36
+ decodeA2AAgentCard,
37
+ decodeA2ARpcRequest,
38
+ encodeA2AError,
39
+ encodeA2AEvent,
40
+ encodeA2AResult,
41
+ parseA2AJson,
42
+ parseA2AVersion,
43
+ type A2AAgentCard,
44
+ type A2ADialect,
45
+ type A2AEvent,
46
+ type A2AJson,
47
+ type A2ALimits,
48
+ type A2AMessage,
49
+ type A2AObject,
50
+ type A2APart,
51
+ type A2APushConfig,
52
+ type A2ARequest,
53
+ type A2AResponse,
54
+ type A2ARpcId,
55
+ type A2ASendParams,
56
+ type A2ATask,
57
+ type A2AVersion,
58
+ } from "./wire.ts";
59
+
60
+ export interface A2AProjectionContext {
61
+ principal: A2APrincipal;
62
+ tenant?: string;
63
+ taskId: string;
64
+ contextId: string;
65
+ }
66
+ export interface A2AServerBase<O> {
67
+ tasks: A2ATaskStore;
68
+ card: {
69
+ url: string;
70
+ name: string;
71
+ description: string;
72
+ version?: string;
73
+ skills?: A2AObject[];
74
+ security?: Partial<Record<A2AVersion, { schemes: A2AObject; requirements: A2AObject[] }>>;
75
+ extensions?: A2AObject[];
76
+ provider?: { organization: string; url: string };
77
+ };
78
+ authenticate?: A2AAuthenticate;
79
+ /** Development only. One fixed anonymous partition; never fall back after failed auth. */
80
+ allowAnonymous?: boolean;
81
+ /** Only the discovery card may bypass authentication. Defaults to false. */
82
+ publicCard?: boolean;
83
+ /** Host-selected tenant for this handler. Request tenant fields cannot change it. */
84
+ tenant?: string;
85
+ /** Opt in only when runs has an owner-checked session factory. Otherwise context IDs group
86
+ * tasks without loading conversation history. Never infer session access from the ID. */
87
+ sessions?: boolean;
88
+ /** Current access check, also called for each emitted stream frame and background push.
89
+ * Authentication still runs first. False is indistinguishable from a missing task. */
90
+ authorize?: (context: {
91
+ principal: A2APrincipal;
92
+ tenant?: string;
93
+ operation: string;
94
+ taskId?: string;
95
+ }) => boolean | Promise<boolean>;
96
+ remoteApprovals?: boolean;
97
+ remoteClientTools?: boolean;
98
+ /** Trusted output allowlist. Omitted means no result content leaves the process. */
99
+ projectOutput?: (
100
+ outcome: Extract<NodeOutcome<O>, { status: "completed" }>,
101
+ context: A2AProjectionContext,
102
+ ) => A2APart[] | Promise<A2APart[]>;
103
+ /** Root text only, no reasoning/tools/children. Omitted means no transient text is exposed. */
104
+ projectText?: (
105
+ text: string,
106
+ context: A2AProjectionContext,
107
+ ) => string | undefined | Promise<string | undefined>;
108
+ /** May narrow request visibility, never expand actor ownership or approval policy. */
109
+ exposeRequest?: (request: PendingRequest, context: A2AProjectionContext) => boolean;
110
+ extendedCard?: (
111
+ principal: A2APrincipal,
112
+ version: A2AVersion,
113
+ ) => A2AAgentCard | Promise<A2AAgentCard>;
114
+ push?: A2APushPolicy;
115
+ sign?: A2ACardSigner;
116
+ describeFailure?: (failure: RunFailure | { limit: string }) => string;
117
+ limits?: Partial<A2ALimits> & {
118
+ blockMs?: number;
119
+ inlineBytes?: number;
120
+ pushConfigs?: number;
121
+ hops?: number;
122
+ };
123
+ }
124
+ export type A2AServerOptions<I = AgentInput, O = unknown> = A2AServerBase<O> &
125
+ (
126
+ | { runs: A2ARuns<AgentInput, O>; prepare?: undefined }
127
+ | {
128
+ runs: A2ARuns<I, O>;
129
+ prepare: (
130
+ message: A2AMessage,
131
+ context: { principal: A2APrincipal; request: Request },
132
+ ) => I | Promise<I>;
133
+ }
134
+ );
135
+ export class A2ATaskRejected extends Error {
136
+ constructor() {
137
+ super("The host refused this task.");
138
+ this.name = "A2ATaskRejected";
139
+ }
140
+ }
141
+
142
+ /** Maps content only, never settings, instructions or tools. URL parts require the host's
143
+ * prepare callback; this function never fetches them. JSON parts are untrusted input text. */
144
+ export function a2aInput(message: A2AMessage, inlineBytes = 10 * 1024 * 1024): AgentInput {
145
+ let bytes = 0;
146
+ const parts: InputPart[] = message.parts.map((part): InputPart => {
147
+ if (part.kind === "text") return { type: "text", text: part.text };
148
+ if (part.kind === "data")
149
+ return { type: "text", text: `Untrusted message data:\n${canonicalA2AJson(part.data)}` };
150
+ if (part.kind === "url") throw new A2AError("protocol", { code: -32005 });
151
+ const raw = part.raw.replaceAll("-", "+").replaceAll("_", "/");
152
+ let decoded: string;
153
+ try {
154
+ decoded = atob(raw);
155
+ } catch {
156
+ throw new A2AError("invalid");
157
+ }
158
+ bytes += decoded.length;
159
+ if (bytes > inlineBytes) throw new A2AError("limit");
160
+ const data = btoa(decoded);
161
+ if (isImageMime(part.mediaType)) return { type: "image", data, mimeType: part.mediaType };
162
+ if (isFileMime(part.mediaType)) return { type: "file", data, mimeType: part.mediaType };
163
+ throw new A2AError("protocol", { code: -32005 });
164
+ });
165
+ return parts;
166
+ }
167
+ function json(value: unknown): A2AJson {
168
+ return parseA2AJson(JSON.stringify(value));
169
+ }
170
+ function object(value: unknown): A2AObject {
171
+ const result = json(value);
172
+ if (!result || typeof result !== "object" || Array.isArray(result)) throw new A2AError("invalid");
173
+ return result;
174
+ }
175
+ function protocol(code: number): never {
176
+ throw new A2AError("protocol", { code });
177
+ }
178
+ function positive(value: number): number {
179
+ if (!Number.isSafeInteger(value) || value < 1) throw new A2AError("invalid");
180
+ return value;
181
+ }
182
+ function historyMessage(message: A2AMessage, task: A2ATaskRecord): A2AMessage | undefined {
183
+ const parts = message.parts
184
+ .filter((part) => part.kind === "text")
185
+ .map((part) => ({ kind: "text" as const, text: part.text }));
186
+ return parts.length
187
+ ? {
188
+ kind: "message",
189
+ messageId: message.messageId,
190
+ role: message.role,
191
+ parts,
192
+ taskId: task.id,
193
+ contextId: task.contextId,
194
+ }
195
+ : undefined;
196
+ }
197
+ function context(record: A2ATaskRecord): A2AProjectionContext {
198
+ return {
199
+ principal: { owner: record.owner, actorId: record.actorId },
200
+ tenant: record.tenant,
201
+ taskId: record.id,
202
+ contextId: record.contextId,
203
+ };
204
+ }
205
+
206
+ /** CAS retries only pure record updates, never start/resume/send/cancel or network writes. */
207
+ async function patchTask(
208
+ tasks: A2ATaskStore,
209
+ scope: A2ATaskScope,
210
+ id: string,
211
+ update: (record: A2ATaskRecord) => A2ATaskPatch | undefined,
212
+ ) {
213
+ for (let attempt = 0; ; attempt++) {
214
+ const record = await tasks.get(scope, id);
215
+ if (!record) protocol(-32001);
216
+ const changes = update(record);
217
+ if (!changes) return record;
218
+ try {
219
+ return await tasks.update(scope, id, changes, record.revision);
220
+ } catch (error) {
221
+ if (!(error instanceof A2ATaskConflict) || attempt === 3) throw error;
222
+ }
223
+ }
224
+ }
225
+ async function receipt(
226
+ tasks: A2ATaskStore,
227
+ scope: A2ATaskScope,
228
+ id: string,
229
+ messageId: string,
230
+ acceptance: A2AMessageReceipt["acceptance"],
231
+ segment?: string,
232
+ ) {
233
+ return patchTask(tasks, scope, id, (current) => {
234
+ const message = current.messages.find((m) => m.id === messageId);
235
+ if (!message) throw new A2AError("invalid");
236
+ // A host claim may finish before the queue reply fails. Never downgrade that evidence.
237
+ if (message.acceptance === "accepted") {
238
+ if (segment && message.segment !== segment) throw new A2ATaskConflict();
239
+ return undefined;
240
+ }
241
+ return {
242
+ messages: current.messages.map((m) =>
243
+ m.id === messageId ? { ...m, acceptance, ...(segment ? { segment } : {}) } : m,
244
+ ),
245
+ ...(segment && (!current.segment || current.segment === message.source) ? { segment } : {}),
246
+ };
247
+ });
248
+ }
249
+
250
+ /** Web-standard handler. Work belongs to runs, not to the request or a stream reader. The
251
+ * host must retain the process for memory runs; production uses a durable run-service binding. */
252
+ export function createA2AServer<I = AgentInput, O = unknown>(options: A2AServerOptions<I, O>) {
253
+ if (!options.authenticate && !options.allowAnonymous)
254
+ throw new TypeError(
255
+ "Provide authenticate before serving tasks. Use allowAnonymous only for local development.",
256
+ );
257
+ const { tasks, runs } = options;
258
+ const {
259
+ blockMs: block = 60_000,
260
+ inlineBytes = 10 * 1024 * 1024,
261
+ pushConfigs = 10,
262
+ hops: maxHops = 16,
263
+ ...wireLimits
264
+ } = options.limits ?? {};
265
+ const limits = a2aLimits(wireLimits);
266
+ const blockMs = positive(block);
267
+ positive(inlineBytes);
268
+ positive(pushConfigs);
269
+ positive(maxHops);
270
+ const base = new URL(options.card.url);
271
+ if (
272
+ base.username ||
273
+ base.password ||
274
+ base.search ||
275
+ base.hash ||
276
+ !["https:", "http:"].includes(base.protocol)
277
+ )
278
+ throw new A2AError("invalid");
279
+ base.pathname = `${base.pathname.replace(/\/+$/, "")}/`;
280
+ const rpcUrl = new URL("jsonrpc", base);
281
+ const restUrl = new URL("rest", base);
282
+ const cardPath = new URL(".well-known/agent-card.json", base).pathname;
283
+ const stopped = new AbortController();
284
+ const watchers = new Map<string, Promise<void>>();
285
+ async function principal(request: Request): Promise<A2APrincipal | null> {
286
+ return options.authenticate
287
+ ? authenticateA2A(request, options.authenticate)
288
+ : options.allowAnonymous
289
+ ? { owner: "anonymous", actorId: "anonymous" }
290
+ : null;
291
+ }
292
+ function scope(p: A2APrincipal): A2ATaskScope {
293
+ return { ...p, ...(options.tenant ? { tenant: options.tenant } : {}) };
294
+ }
295
+ async function access(s: A2ATaskScope, operation: string, taskId?: string, request?: Request) {
296
+ if (request) {
297
+ const current = await principal(request);
298
+ if (!current || current.owner !== s.owner || current.actorId !== s.actorId) protocol(-32001);
299
+ }
300
+ if (
301
+ options.authorize &&
302
+ !(await options.authorize({
303
+ principal: { owner: s.owner, actorId: s.actorId },
304
+ tenant: s.tenant,
305
+ operation,
306
+ taskId,
307
+ }))
308
+ )
309
+ protocol(-32001);
310
+ }
311
+ async function get(s: A2ATaskScope, id: string, operation: string, request?: Request) {
312
+ await access(s, operation, id, request);
313
+ const record = await tasks.get(s, id);
314
+ if (!record) protocol(-32001);
315
+ return record;
316
+ }
317
+ function visibleRequest(request: PendingRequest, record: A2ATaskRecord): boolean {
318
+ return (
319
+ request.scope.actorId === record.actorId &&
320
+ (request.ask.type === "question" ||
321
+ (request.ask.type === "approval" && options.remoteApprovals === true) ||
322
+ (request.ask.type === "client" && options.remoteClientTools === true)) &&
323
+ (!options.exposeRequest || options.exposeRequest(immutableCopy(request), context(record)))
324
+ );
325
+ }
326
+ function offered(row: A2ARun<O>, record: A2ATaskRecord): ReturnType<typeof openRequests> {
327
+ return openRequests(row.snapshot).filter(
328
+ (request) => request.scope.expiresAt > Date.now() && visibleRequest(request, record),
329
+ );
330
+ }
331
+ function requestMessage(
332
+ record: A2ATaskRecord,
333
+ messageId: string,
334
+ requests: ReturnType<typeof openRequests>,
335
+ ): A2AMessage {
336
+ const data = requests.map((r) => ({
337
+ id: r.id,
338
+ type: r.ask.type,
339
+ ...(r.ask.type === "client" ? { schema: r.ask.resultSchema } : { message: r.ask.message }),
340
+ ...(r.ask.type === "question"
341
+ ? {
342
+ choices: r.ask.choices,
343
+ multiple: r.ask.multiple,
344
+ freeText: r.ask.freeText,
345
+ schema: r.ask.schema,
346
+ }
347
+ : {}),
348
+ expiresAt: r.scope.expiresAt,
349
+ ...(r.problem
350
+ ? {
351
+ problem: {
352
+ code: r.problem.code,
353
+ message: "That answer was not accepted. Check the question and send a new answer.",
354
+ },
355
+ }
356
+ : {}),
357
+ }));
358
+ return {
359
+ kind: "message",
360
+ role: "agent",
361
+ taskId: record.id,
362
+ contextId: record.contextId,
363
+ messageId,
364
+ parts: [
365
+ {
366
+ kind: "text",
367
+ text: requests
368
+ .map((r) =>
369
+ r.ask.type === "client"
370
+ ? "The host needs a client result."
371
+ : (r.ask.message ?? "An action needs approval."),
372
+ )
373
+ .join("\n"),
374
+ },
375
+ { kind: "data", data: object({ requests: data }) },
376
+ ],
377
+ };
378
+ }
379
+ async function project(record: A2ATaskRecord, row?: A2ARun<O>): Promise<A2ATask> {
380
+ let state = record.state;
381
+ let message: A2AMessage | undefined;
382
+ let parts: A2APart[] = [];
383
+ const say = (text: string) => {
384
+ message = {
385
+ kind: "message",
386
+ role: "agent",
387
+ taskId: record.id,
388
+ contextId: record.contextId,
389
+ messageId: `${record.id}:status`,
390
+ parts: [{ kind: "text", text }],
391
+ };
392
+ };
393
+ if (!row) {
394
+ if (
395
+ record.messages.some((m) => m.acceptance === "unknown") ||
396
+ (record.state !== "rejected" && Date.now() - record.createdAt >= 60_000)
397
+ ) {
398
+ state = "unknown";
399
+ say("The task may have started. Check its status before sending more work.");
400
+ }
401
+ } else if (row.status === "cancelled" && row.outcome?.status !== "completed")
402
+ state = "canceled";
403
+ else if (row.status === "failed" && row.outcome?.status !== "completed") {
404
+ state = "failed";
405
+ say("The task could not finish. Check with the host before starting it again.");
406
+ } else if (
407
+ (row.status === "queued" || row.status === "running") &&
408
+ row.outcome?.status !== "completed"
409
+ )
410
+ state = row.status === "queued" && record.messages.length === 1 ? "submitted" : "working";
411
+ else if (row.outcome) {
412
+ const result = row.outcome;
413
+ switch (result.status) {
414
+ case "completed":
415
+ state = "completed";
416
+ parts = structuredClone((await options.projectOutput?.(result, context(record))) ?? []);
417
+ if (parts.length)
418
+ message = {
419
+ kind: "message",
420
+ role: "agent",
421
+ messageId: `${record.id}:answer`,
422
+ taskId: record.id,
423
+ contextId: record.contextId,
424
+ parts: structuredClone(parts),
425
+ };
426
+ break;
427
+ case "cancelled":
428
+ state = "canceled";
429
+ say("The task stopped. Work already sent to another service may still finish.");
430
+ break;
431
+ case "limited":
432
+ state = "failed";
433
+ say(
434
+ options.describeFailure?.({ limit: result.limit }) ??
435
+ "The task reached its limit. Check its saved result before starting more work.",
436
+ );
437
+ break;
438
+ case "failed":
439
+ state = "failed";
440
+ say(
441
+ options.describeFailure?.(result.error) ??
442
+ "The task could not finish. Check with the host before starting it again.",
443
+ );
444
+ break;
445
+ case "suspended": {
446
+ const requests = offered(row, record);
447
+ state = requests.length ? "input_required" : "working";
448
+ if (Date.now() >= row.snapshot.tree.startedAt + row.snapshot.tree.limits.elapsedMs) {
449
+ state = "failed";
450
+ say("The task waited too long for an answer. Start a new task.");
451
+ break;
452
+ }
453
+ if (requests.length)
454
+ message = requestMessage(
455
+ record,
456
+ `${record.id}:request:${row.snapshot.attemptId}`,
457
+ requests,
458
+ );
459
+ else
460
+ say(
461
+ row.wakeAt === undefined
462
+ ? "Waiting for the operator to continue this task."
463
+ : "Waiting for the scheduled continuation.",
464
+ );
465
+ break;
466
+ }
467
+ }
468
+ }
469
+ const publicTask: A2ATask = {
470
+ kind: "task",
471
+ id: record.id,
472
+ contextId: record.contextId,
473
+ status: {
474
+ state,
475
+ ...(message ? { message } : {}),
476
+ timestamp: new Date(record.updatedAt).toISOString(),
477
+ },
478
+ ...(parts.length ? { artifacts: [{ artifactId: "answer", parts }] } : {}),
479
+ };
480
+ // Validate all host projections before putting them on the wire or in public history.
481
+ encodeA2AEvent(publicTask, { version: "1.0", binding: "JSONRPC" });
482
+ return publicTask;
483
+ }
484
+ async function view(
485
+ s: A2ATaskScope,
486
+ id: string,
487
+ operation = "GetTask",
488
+ request?: Request,
489
+ historyLength = 100,
490
+ ): Promise<{ task: A2ATask; record: A2ATaskRecord; row?: A2ARun<O> }> {
491
+ let record = await get(s, id, operation, request);
492
+ const row = record.segment ? await runs.read(s.owner, record.segment) : undefined;
493
+ if (row && row.snapshot.runId !== id) throw new A2AError("invalid");
494
+ const task = await project(record, row);
495
+ const publicMessage = task.status.message;
496
+ record = await patchTask(tasks, s, id, (current) => {
497
+ // A continuation can win while this read projects an older segment. Never regress it.
498
+ if (current.segment !== record.segment) return undefined;
499
+ const history =
500
+ publicMessage && !current.history.some((m) => m.messageId === publicMessage.messageId)
501
+ ? [...current.history, publicMessage].slice(-100)
502
+ : current.history;
503
+ if (current.state === task.status.state && history === current.history) return undefined;
504
+ if (a2aTerminal(current.state) && current.state !== task.status.state) return undefined;
505
+ return { state: task.status.state, history };
506
+ });
507
+ if (row && record.segment !== row.id) return view(s, id, operation, request, historyLength);
508
+ task.status.timestamp = new Date(record.updatedAt).toISOString();
509
+ if (historyLength > 0) {
510
+ const requests = new Map(
511
+ row
512
+ ? [...requestRecords(row.snapshot)].map(({ record: r }) => [r.request.id, r.request])
513
+ : [],
514
+ );
515
+ // Stored projections are a cache, not continuing permission. Rebuild agent content from
516
+ // the current output/request policy; obsolete statuses have no independent disclosure.
517
+ const history = record.history.flatMap((message): A2AMessage[] => {
518
+ if (message.role === "user") return [message];
519
+ if (message.messageId === publicMessage?.messageId) return [publicMessage];
520
+ if (!message.messageId.startsWith(`${id}:request:`)) return [];
521
+ const visible = message.parts.flatMap((part) => {
522
+ if (part.kind !== "data" || !isRecord(part.data) || !Array.isArray(part.data.requests))
523
+ return [];
524
+ return part.data.requests.flatMap((value) => {
525
+ const request =
526
+ isRecord(value) && typeof value.id === "string" ? requests.get(value.id) : undefined;
527
+ return request && visibleRequest(request, record) ? [request] : [];
528
+ });
529
+ });
530
+ return visible.length ? [requestMessage(record, message.messageId, visible)] : [];
531
+ });
532
+ task.history = structuredClone(history.slice(-Math.min(historyLength, 100)));
533
+ }
534
+ await access(s, operation, id, request);
535
+ return { task, record, row };
536
+ }
537
+ async function notify(s: A2ATaskScope, id: string) {
538
+ if (!options.push) return;
539
+ const current = await view(s, id, "Push");
540
+ await deliverA2APush({
541
+ tasks,
542
+ scope: s,
543
+ taskId: id,
544
+ event: current.task,
545
+ policy: options.push,
546
+ });
547
+ }
548
+ function watch(s: A2ATaskScope, id: string) {
549
+ if (!options.push) return;
550
+ const key = JSON.stringify([s, id]);
551
+ if (watchers.has(key) || stopped.signal.aborted) return;
552
+ const watching = (async () => {
553
+ for (;;) {
554
+ stopped.signal.throwIfAborted();
555
+ const current = await view(s, id, "Push");
556
+ await notify(s, id);
557
+ if (a2aStateClosed(current.task.status.state)) return;
558
+ await sleep(250, stopped.signal);
559
+ }
560
+ })()
561
+ .catch(() => {
562
+ /* No replay after uncertain writes or revoked access. Host can refresh. */
563
+ })
564
+ .finally(() => {
565
+ watchers.delete(key);
566
+ });
567
+ watchers.set(key, watching);
568
+ }
569
+ async function pushConfig(s: A2ATaskScope, config: A2APushConfig, d: A2ADialect) {
570
+ if (!options.push) protocol(-32003);
571
+ const validated = structuredClone({
572
+ ...config,
573
+ id: config.id ?? crypto.randomUUID(),
574
+ ...(s.tenant ? { tenant: s.tenant } : {}),
575
+ });
576
+ await checkA2APushConfig(validated, s, options.push);
577
+ return { config: validated, dialect: d };
578
+ }
579
+ async function accept(
580
+ s: A2ATaskScope,
581
+ params: A2ASendParams,
582
+ request: Request,
583
+ dialect: A2ADialect,
584
+ ): Promise<string> {
585
+ const message = params.message;
586
+ const fingerprint = await hashA2AJson(object(params));
587
+ const existing = await tasks.findMessage(s, message.messageId);
588
+ if (existing) {
589
+ await access(s, "SendMessage", existing.id, request);
590
+ if (existing.messages.find((m) => m.id === message.messageId)?.fingerprint !== fingerprint)
591
+ protocol(-32602);
592
+ return existing.id;
593
+ }
594
+ if (message.referenceTaskIds?.length) protocol(-32004);
595
+ if (message.taskId) {
596
+ const current = await view(s, message.taskId, "SendMessage", request);
597
+ if (message.contextId && message.contextId !== current.record.contextId) protocol(-32602);
598
+ if (
599
+ a2aTerminal(current.task.status.state) ||
600
+ (current.record.cancel && current.record.cancel !== "refused") ||
601
+ current.record.messages.some(
602
+ (receipt) => receipt.kind !== "start" && receipt.acceptance !== "accepted",
603
+ )
604
+ )
605
+ protocol(-32004);
606
+ if (!current.record.segment || !current.row) protocol(-32004);
607
+ if (params.configuration?.pushNotificationConfig) protocol(-32004);
608
+ const open = offered(current.row, current.record);
609
+ let answers: Record<string, unknown> | undefined;
610
+ let input: AgentInput | undefined;
611
+ const kind = current.task.status.state === "input_required" ? "resume" : "steer";
612
+ if (kind === "resume") {
613
+ const maps = message.parts.filter(
614
+ (part) =>
615
+ part.kind === "data" && isRecord(part.data) && Object.hasOwn(part.data, "answers"),
616
+ );
617
+ let values: Record<string, unknown>;
618
+ if (
619
+ maps.length === 1 &&
620
+ maps[0]?.kind === "data" &&
621
+ isRecord(maps[0].data) &&
622
+ isRecord(maps[0].data.answers)
623
+ )
624
+ values = maps[0].data.answers;
625
+ else if (
626
+ !maps.length &&
627
+ message.parts.every((part) => part.kind === "text") &&
628
+ open.length === 1 &&
629
+ open[0]?.ask.type === "question" &&
630
+ open[0].ask.freeText === true
631
+ )
632
+ values = {
633
+ [open[0].id]: {
634
+ type: "answer",
635
+ answer: {
636
+ text: message.parts
637
+ .map((part) => (part.kind === "text" ? part.text : ""))
638
+ .join("\n"),
639
+ },
640
+ },
641
+ };
642
+ else protocol(-32602);
643
+ if (
644
+ !Object.keys(values).length ||
645
+ Object.keys(values).some((id) => !open.some((r) => r.id === id))
646
+ )
647
+ protocol(-32602);
648
+ answers = Object.fromEntries(
649
+ Object.entries(values).map(([id, answer]) => [
650
+ id,
651
+ {
652
+ via: "a2a",
653
+ ...taskScope(s),
654
+ taskId: current.record.id,
655
+ messageId: message.messageId,
656
+ requestId: id,
657
+ answer: copyData(answer),
658
+ },
659
+ ]),
660
+ );
661
+ } else {
662
+ if (
663
+ !runs.send ||
664
+ current.row.status !== "running" ||
665
+ !message.parts.every((p) => p.kind === "text")
666
+ )
667
+ protocol(-32004);
668
+ input = a2aInput(message, inlineBytes);
669
+ }
670
+ const publicMessage = historyMessage(message, current.record);
671
+ const claim: A2AMessageReceipt = {
672
+ id: message.messageId,
673
+ fingerprint,
674
+ kind,
675
+ acceptance: "pending",
676
+ source: current.record.segment,
677
+ ...(answers ? { answers } : {}),
678
+ };
679
+ // One CAS before the effect. A competing continuation is refused, not retried.
680
+ await tasks.update(
681
+ s,
682
+ current.record.id,
683
+ {
684
+ messages: [...current.record.messages, claim],
685
+ history: [...current.record.history, ...(publicMessage ? [publicMessage] : [])].slice(
686
+ -100,
687
+ ),
688
+ state: "working",
689
+ },
690
+ current.record.revision,
691
+ );
692
+ let next: string | undefined;
693
+ try {
694
+ await access(s, kind, current.record.id, request);
695
+ if (answers) next = (await runs.resume(s.owner, current.record.segment, answers)).id;
696
+ else {
697
+ if (
698
+ !runs.send ||
699
+ input === undefined ||
700
+ (typeof input === "object" && "messages" in input)
701
+ )
702
+ protocol(-32004);
703
+ await runs.send(s.owner, current.record.segment, {
704
+ id: message.messageId,
705
+ content: typeof input === "string" ? input : [...input],
706
+ });
707
+ }
708
+ await receipt(tasks, s, current.record.id, message.messageId, "accepted", next);
709
+ } catch (error) {
710
+ await receipt(tasks, s, current.record.id, message.messageId, "unknown", next);
711
+ throw error;
712
+ }
713
+ watch(s, current.record.id);
714
+ return current.record.id;
715
+ }
716
+ if (message.contextId && !(await tasks.hasContext(s, message.contextId))) protocol(-32602);
717
+ const hops = params.metadata?.["providerkit.hops"] ?? 0;
718
+ if (typeof hops !== "number" || !Number.isSafeInteger(hops) || hops < 0 || hops > maxHops)
719
+ protocol(-32602);
720
+ const preparedInput = options.prepare ? undefined : a2aInput(message, inlineBytes);
721
+ const id = crypto.randomUUID();
722
+ const record: A2ATaskRecord = {
723
+ ...s,
724
+ id,
725
+ contextId: message.contextId ?? crypto.randomUUID(),
726
+ hops,
727
+ state: "submitted",
728
+ messages: [{ id: message.messageId, fingerprint, kind: "start", acceptance: "pending" }],
729
+ history: [],
730
+ push: [],
731
+ deliveries: [],
732
+ createdAt: Date.now(),
733
+ updatedAt: Date.now(),
734
+ revision: "",
735
+ };
736
+ const publicMessage = historyMessage(message, record);
737
+ if (publicMessage) record.history.push(publicMessage);
738
+ if (params.configuration?.pushNotificationConfig)
739
+ record.push.push(
740
+ await pushConfig(
741
+ s,
742
+ { ...params.configuration.pushNotificationConfig, taskId: id },
743
+ dialect,
744
+ ),
745
+ );
746
+ const created = await tasks.create(record);
747
+ if (!created.created) return created.record.id;
748
+ let segment: string | undefined;
749
+ try {
750
+ await access(s, "start", id, request);
751
+ const start = { runId: id, ...(options.sessions ? { sessionId: record.contextId } : {}) };
752
+ // The request's abort only detaches after reservation. No uncertain start is repeated.
753
+ if (options.prepare) {
754
+ const input = await options.prepare(immutableCopy(message), {
755
+ principal: { owner: s.owner, actorId: s.actorId },
756
+ request,
757
+ });
758
+ await access(s, "start", id, request);
759
+ segment = (await options.runs.start(s.owner, input, start)).id;
760
+ } else {
761
+ if (preparedInput === undefined) throw new A2AError("invalid");
762
+ segment = (await options.runs.start(s.owner, preparedInput, start)).id;
763
+ }
764
+ await receipt(tasks, s, id, message.messageId, "accepted", segment);
765
+ } catch (error) {
766
+ await receipt(
767
+ tasks,
768
+ s,
769
+ id,
770
+ message.messageId,
771
+ error instanceof A2ATaskRejected ? "accepted" : "unknown",
772
+ segment,
773
+ );
774
+ if (error instanceof A2ATaskRejected) {
775
+ await patchTask(tasks, s, id, () => ({ state: "rejected" }));
776
+ return id;
777
+ }
778
+ throw error;
779
+ }
780
+ watch(s, id);
781
+ return id;
782
+ }
783
+ async function wait(s: A2ATaskScope, id: string, request: Request, historyLength?: number) {
784
+ const deadline = Date.now() + blockMs;
785
+ for (;;) {
786
+ const current = await view(s, id, "SendMessage", request, historyLength);
787
+ if (a2aStateClosed(current.task.status.state) || Date.now() >= deadline) return current.task;
788
+ await sleep(Math.min(25, Math.max(1, deadline - Date.now())), request.signal);
789
+ }
790
+ }
791
+ async function* events(
792
+ s: A2ATaskScope,
793
+ id: string,
794
+ request: Request,
795
+ signal: AbortSignal,
796
+ historyLength?: number,
797
+ ): AsyncGenerator<A2AEvent> {
798
+ let current = await view(s, id, "SubscribeToTask", request, historyLength);
799
+ yield current.task;
800
+ let previous = canonicalA2AJson(object(current.task));
801
+ let operation: string | undefined;
802
+ let hasArtifact = !!current.task.artifacts?.length;
803
+ while (!a2aStateClosed(current.task.status.state)) {
804
+ signal.throwIfAborted();
805
+ if (!current.record.segment) throw new A2AError("stream-cut");
806
+ const segment = current.record.segment;
807
+ for await (const stored of runs.observe(s.owner, segment, 0, signal)) {
808
+ signal.throwIfAborted();
809
+ await access(s, "SubscribeToTask", id, request);
810
+ if (stored.type === "agent.gap" || stored.type === "agent.resync") {
811
+ current = await view(s, id, "SubscribeToTask", request, historyLength);
812
+ yield current.task;
813
+ previous = canonicalA2AJson(object(current.task));
814
+ operation = undefined;
815
+ hasArtifact = !!current.task.artifacts?.length;
816
+ if (a2aStateClosed(current.task.status.state)) return;
817
+ continue;
818
+ }
819
+ const delta = await text(stored, current.record);
820
+ if (delta) {
821
+ const append = operation === delta.operation && hasArtifact;
822
+ yield {
823
+ kind: "artifact-update",
824
+ taskId: id,
825
+ contextId: current.record.contextId,
826
+ artifact: { artifactId: "answer", parts: [{ kind: "text", text: delta.text }] },
827
+ append,
828
+ lastChunk: false,
829
+ };
830
+ operation = delta.operation;
831
+ hasArtifact = true;
832
+ }
833
+ }
834
+ // Every authoritative read goes through emission before closure, including a continuation
835
+ // that finishes entirely between polls of an operator-only suspension.
836
+ for (;;) {
837
+ current = await view(s, id, "SubscribeToTask", request, historyLength);
838
+ const value = canonicalA2AJson(object(current.task));
839
+ if (value !== previous) {
840
+ if (current.task.artifacts?.length)
841
+ for (const artifact of current.task.artifacts)
842
+ yield {
843
+ kind: "artifact-update",
844
+ taskId: id,
845
+ contextId: current.record.contextId,
846
+ artifact,
847
+ append: false,
848
+ lastChunk: true,
849
+ };
850
+ else if (hasArtifact)
851
+ yield {
852
+ kind: "artifact-update",
853
+ taskId: id,
854
+ contextId: current.record.contextId,
855
+ artifact: { artifactId: "answer", parts: [{ kind: "text", text: "" }] },
856
+ append: false,
857
+ lastChunk: true,
858
+ };
859
+ yield {
860
+ kind: "status-update",
861
+ taskId: id,
862
+ contextId: current.record.contextId,
863
+ status: current.task.status,
864
+ };
865
+ previous = value;
866
+ hasArtifact = !!current.task.artifacts?.length;
867
+ }
868
+ if (a2aStateClosed(current.task.status.state)) return;
869
+ if (current.record.segment !== segment) break;
870
+ if (current.row && ["queued", "running"].includes(current.row.status))
871
+ throw new A2AError("stream-cut");
872
+ await sleep(250, signal);
873
+ }
874
+ }
875
+ }
876
+ async function text(stored: A2AStoredEvent, record: A2ATaskRecord) {
877
+ const data = stored.data;
878
+ if (
879
+ !options.projectText ||
880
+ stored.type !== "agent" ||
881
+ !isRecord(data) ||
882
+ data.type !== "model_chunk" ||
883
+ data.runId !== record.id ||
884
+ typeof data.operationId !== "string" ||
885
+ typeof data.attemptId !== "string" ||
886
+ !isRecord(data.chunk) ||
887
+ data.chunk.type !== "delta" ||
888
+ typeof data.chunk.content !== "string"
889
+ )
890
+ return undefined;
891
+ const value = await options.projectText(data.chunk.content, context(record));
892
+ return value
893
+ ? { text: value, operation: JSON.stringify([data.operationId, data.attemptId]) }
894
+ : undefined;
895
+ }
896
+ function stream(
897
+ s: A2ATaskScope,
898
+ id: string,
899
+ request: Request,
900
+ d: A2ADialect,
901
+ rpcId: A2ARpcId | null,
902
+ historyLength?: number,
903
+ ) {
904
+ const detached = new AbortController();
905
+ const signal = AbortSignal.any([detached.signal, request.signal, stopped.signal]);
906
+ const iterator = events(s, id, request, signal, historyLength);
907
+ let pending: Promise<IteratorResult<A2AEvent>> | undefined;
908
+ let ended = false;
909
+ const encoder = new TextEncoder();
910
+ const body = new ReadableStream<Uint8Array>(
911
+ {
912
+ async pull(controller) {
913
+ if (ended) return;
914
+ let timer: ReturnType<typeof setTimeout> | undefined;
915
+ try {
916
+ pending ??= iterator.next();
917
+ const next = await untilAbort(
918
+ Promise.race([
919
+ pending,
920
+ new Promise<null>((resolve) => {
921
+ timer = setTimeout(() => resolve(null), 15_000);
922
+ }),
923
+ ]),
924
+ signal,
925
+ );
926
+ if (next === null) {
927
+ await access(s, "SubscribeToTask", id, request);
928
+ controller.enqueue(encoder.encode(": keep-alive\n\n"));
929
+ return;
930
+ }
931
+ pending = undefined;
932
+ if (next.done) {
933
+ ended = true;
934
+ controller.close();
935
+ return;
936
+ }
937
+ await access(s, "SubscribeToTask", id, request);
938
+ const value = encodeA2AEvent(next.value, d);
939
+ controller.enqueue(
940
+ encoder.encode(
941
+ `data: ${JSON.stringify(d.binding === "JSONRPC" ? { jsonrpc: "2.0", id: rpcId, result: value } : value)}\n\n`,
942
+ ),
943
+ );
944
+ } catch (error) {
945
+ ended = true;
946
+ if (!signal.aborted) {
947
+ const failure = encodeA2AError(
948
+ error instanceof A2AError ? (error.code ?? -32603) : -32603,
949
+ d,
950
+ rpcId,
951
+ );
952
+ controller.enqueue(
953
+ encoder.encode(`event: error\ndata: ${JSON.stringify(failure.body)}\n\n`),
954
+ );
955
+ }
956
+ controller.close();
957
+ detached.abort();
958
+ void iterator.return(undefined).catch(() => {});
959
+ } finally {
960
+ clearTimeout(timer);
961
+ }
962
+ },
963
+ cancel() {
964
+ ended = true;
965
+ detached.abort();
966
+ void iterator.return(undefined).catch(() => {});
967
+ },
968
+ },
969
+ { highWaterMark: 0 },
970
+ );
971
+ return new Response(body, {
972
+ headers: {
973
+ "content-type": "text/event-stream",
974
+ "cache-control": "no-store",
975
+ "A2A-Version": d.version,
976
+ },
977
+ });
978
+ }
979
+ async function card(version: A2AVersion = "1.0"): Promise<A2AAgentCard> {
980
+ const host = options.card;
981
+ const security = host.security?.[version];
982
+ const capabilities = {
983
+ streaming: true,
984
+ pushNotifications: !!options.push,
985
+ ...(version === "1.0" ? { extendedAgentCard: !!options.extendedCard } : {}),
986
+ extensions: host.extensions ?? [],
987
+ };
988
+ const common = {
989
+ name: host.name,
990
+ description: host.description,
991
+ version: host.version ?? "1",
992
+ skills: host.skills ?? [],
993
+ defaultInputModes: ["text/plain", "application/json"],
994
+ defaultOutputModes: ["text/plain", "application/json"],
995
+ capabilities,
996
+ ...(security
997
+ ? {
998
+ securitySchemes: security.schemes,
999
+ [version === "1.0" ? "securityRequirements" : "security"]: security.requirements,
1000
+ }
1001
+ : {}),
1002
+ ...(host.provider ? { provider: host.provider } : {}),
1003
+ };
1004
+ const document =
1005
+ version === "1.0"
1006
+ ? {
1007
+ ...common,
1008
+ supportedInterfaces: (["1.0", "0.3"] as const).flatMap((v) =>
1009
+ (["JSONRPC", "HTTP+JSON"] as const).map((binding) => ({
1010
+ url: binding === "JSONRPC" ? rpcUrl.href : restUrl.href,
1011
+ protocolBinding: binding,
1012
+ protocolVersion: v,
1013
+ ...(v === "1.0" && options.tenant ? { tenant: options.tenant } : {}),
1014
+ })),
1015
+ ),
1016
+ }
1017
+ : {
1018
+ ...common,
1019
+ protocolVersion: "0.3.0",
1020
+ url: rpcUrl.href,
1021
+ preferredTransport: "JSONRPC",
1022
+ additionalInterfaces: [{ url: restUrl.href, transport: "HTTP+JSON" }],
1023
+ supportsAuthenticatedExtendedCard: !!options.extendedCard,
1024
+ };
1025
+ const decoded = decodeA2AAgentCard(document, version);
1026
+ return options.sign ? signAgentCard(decoded, options.sign) : decoded;
1027
+ }
1028
+ async function operation(
1029
+ s: A2ATaskScope,
1030
+ decoded: A2ARequest,
1031
+ request: Request,
1032
+ d: A2ADialect,
1033
+ rpcId: A2ARpcId | null,
1034
+ ): Promise<A2AResponse | Response> {
1035
+ if (decoded.params.tenant !== undefined && decoded.params.tenant !== s.tenant) protocol(-32001);
1036
+ await access(s, decoded.method, undefined, request);
1037
+ switch (decoded.method) {
1038
+ case "SendMessage":
1039
+ case "SendStreamingMessage": {
1040
+ const id = await accept(s, decoded.params, request, d);
1041
+ if (decoded.method === "SendStreamingMessage")
1042
+ return stream(s, id, request, d, rpcId, decoded.params.configuration?.historyLength);
1043
+ const task = decoded.params.configuration?.returnImmediately
1044
+ ? (await view(s, id, decoded.method, request, decoded.params.configuration.historyLength))
1045
+ .task
1046
+ : await wait(s, id, request, decoded.params.configuration?.historyLength);
1047
+ return { method: "SendMessage", result: task };
1048
+ }
1049
+ case "GetTask":
1050
+ return {
1051
+ method: "GetTask",
1052
+ result: (
1053
+ await view(s, decoded.params.id, decoded.method, request, decoded.params.historyLength)
1054
+ ).task,
1055
+ };
1056
+ case "SubscribeToTask": {
1057
+ const current = await view(s, decoded.params.id, decoded.method, request);
1058
+ if (a2aTerminal(current.task.status.state)) protocol(-32004);
1059
+ return stream(s, decoded.params.id, request, d, rpcId);
1060
+ }
1061
+ case "CancelTask": {
1062
+ const current = await view(s, decoded.params.id, decoded.method, request);
1063
+ if (a2aTerminal(current.task.status.state) || !current.record.segment) protocol(-32002);
1064
+ if (current.record.cancel === "refused") protocol(-32002);
1065
+ if (!current.record.cancel) {
1066
+ await tasks.update(s, current.record.id, { cancel: "pending" }, current.record.revision);
1067
+ try {
1068
+ const result = await runs.cancel(s.owner, current.record.segment);
1069
+ await patchTask(tasks, s, current.record.id, (record) => {
1070
+ // Follow the physical segment even without onSegment. A newer continuation
1071
+ // may have won meanwhile; an old acknowledgement cannot overwrite its ID.
1072
+ if (record.segment !== current.record.segment && record.segment !== result.id)
1073
+ throw new A2ATaskConflict();
1074
+ return { segment: result.id, cancel: result.requested ? "accepted" : "refused" };
1075
+ });
1076
+ if (!result.requested) protocol(-32002);
1077
+ } catch (error) {
1078
+ await patchTask(tasks, s, current.record.id, (r) =>
1079
+ r.cancel === "pending" ? { cancel: "unknown" } : undefined,
1080
+ );
1081
+ throw error;
1082
+ }
1083
+ }
1084
+ watch(s, current.record.id);
1085
+ return {
1086
+ method: "CancelTask",
1087
+ result: (await view(s, current.record.id, decoded.method, request)).task,
1088
+ };
1089
+ }
1090
+ case "ListTasks": {
1091
+ const p = decoded.params;
1092
+ if (p.contextId && !(await tasks.hasContext(s, p.contextId))) protocol(-32001);
1093
+ const size = p.pageSize ?? 50;
1094
+ let cursor: string | undefined;
1095
+ let pastCursor = !p.pageToken;
1096
+ let foundCursor = !p.pageToken;
1097
+ let nextPageToken = "";
1098
+ let totalSize = 0;
1099
+ const result: A2ATask[] = [];
1100
+ const after = p.statusTimestampAfter ? Date.parse(p.statusTimestampAfter) : undefined;
1101
+ if (after !== undefined && !Number.isFinite(after)) protocol(-32602);
1102
+ // Count fresh authorized matches, including those outside this response page.
1103
+ do {
1104
+ const page = await tasks.list(s, {
1105
+ contextId: p.contextId,
1106
+ pageSize: 100,
1107
+ pageToken: cursor,
1108
+ });
1109
+ for (const record of page.tasks) {
1110
+ if (record.id === p.pageToken) {
1111
+ foundCursor = true;
1112
+ pastCursor = true;
1113
+ }
1114
+ let current: Awaited<ReturnType<typeof view>>;
1115
+ try {
1116
+ current = await view(s, record.id, decoded.method, request, p.historyLength ?? 0);
1117
+ } catch (error) {
1118
+ if (error instanceof A2AError && error.code === -32001) continue;
1119
+ throw error;
1120
+ }
1121
+ if (
1122
+ (p.status && current.task.status.state !== p.status) ||
1123
+ (after !== undefined && current.record.updatedAt < after)
1124
+ )
1125
+ continue;
1126
+ totalSize++;
1127
+ if (!pastCursor || record.id === p.pageToken) continue;
1128
+ if (result.length < size) {
1129
+ if (!p.includeArtifacts) delete current.task.artifacts;
1130
+ result.push(current.task);
1131
+ } else if (!nextPageToken) nextPageToken = result.at(-1)!.id;
1132
+ }
1133
+ cursor = page.nextPageToken;
1134
+ } while (cursor);
1135
+ if (!foundCursor) protocol(-32602);
1136
+ return {
1137
+ method: "ListTasks",
1138
+ result: { tasks: result, nextPageToken, pageSize: size, totalSize },
1139
+ };
1140
+ }
1141
+ case "CreateTaskPushNotificationConfig": {
1142
+ if (!decoded.params.taskId) protocol(-32602);
1143
+ const current = await get(s, decoded.params.taskId, decoded.method, request);
1144
+ const configured = await pushConfig(s, decoded.params, d);
1145
+ const previous = current.push.find((p) => p.config.id === configured.config.id);
1146
+ if (previous && d.version === "1.0") protocol(-32602);
1147
+ if (!previous && current.push.length >= Math.min(10, pushConfigs))
1148
+ throw new A2AError("limit");
1149
+ await tasks.update(
1150
+ s,
1151
+ current.id,
1152
+ {
1153
+ push: [...current.push.filter((p) => p.config.id !== configured.config.id), configured],
1154
+ },
1155
+ current.revision,
1156
+ );
1157
+ watch(s, current.id);
1158
+ return { method: decoded.method, result: configured.config };
1159
+ }
1160
+ case "GetTaskPushNotificationConfig":
1161
+ case "ListTaskPushNotificationConfigs":
1162
+ case "DeleteTaskPushNotificationConfig": {
1163
+ const current = await get(s, decoded.params.taskId, decoded.method, request);
1164
+ if (!options.push) protocol(-32003);
1165
+ if (decoded.method === "ListTaskPushNotificationConfigs") {
1166
+ const configs = current.push.map((p) => p.config);
1167
+ const start = decoded.params.pageToken
1168
+ ? configs.findIndex((p) => p.id === decoded.params.pageToken) + 1
1169
+ : 0;
1170
+ if (decoded.params.pageToken && start === 0) protocol(-32602);
1171
+ const end = start + (decoded.params.pageSize ?? 10);
1172
+ const page = configs.slice(start, end);
1173
+ return {
1174
+ method: decoded.method,
1175
+ result: { configs: page, nextPageToken: end < configs.length ? page.at(-1)!.id : "" },
1176
+ };
1177
+ }
1178
+ const config =
1179
+ current.push.find((p) => p.config.id === decoded.params.id) ??
1180
+ (decoded.params.id === undefined && current.push.length === 1
1181
+ ? current.push[0]
1182
+ : undefined);
1183
+ if (!config) protocol(-32001);
1184
+ if (decoded.method === "GetTaskPushNotificationConfig")
1185
+ return { method: decoded.method, result: config.config };
1186
+ await tasks.update(
1187
+ s,
1188
+ current.id,
1189
+ { push: current.push.filter((p) => p.config.id !== config.config.id) },
1190
+ current.revision,
1191
+ );
1192
+ return { method: decoded.method, result: null };
1193
+ }
1194
+ case "GetExtendedAgentCard": {
1195
+ if (!options.extendedCard) protocol(-32007);
1196
+ return {
1197
+ method: decoded.method,
1198
+ result: await options.extendedCard({ owner: s.owner, actorId: s.actorId }, d.version),
1199
+ };
1200
+ }
1201
+ }
1202
+ }
1203
+ return {
1204
+ card,
1205
+ /** Explicit host reconciliation/read, also useful after an out-of-band segment completes. */
1206
+ async refresh(principal: A2APrincipal, id: string) {
1207
+ const s = scope(principal);
1208
+ const current = await view(s, id);
1209
+ await notify(s, id);
1210
+ return current.task;
1211
+ },
1212
+ /** Detaches this handler's observers, never cancels work held by runs. */
1213
+ async close() {
1214
+ stopped.abort();
1215
+ await Promise.all(watchers.values());
1216
+ },
1217
+ async fetch(request: Request): Promise<Response> {
1218
+ const path = new URL(request.url).pathname;
1219
+ let d: A2ADialect = {
1220
+ version: "0.3",
1221
+ binding: path === rpcUrl.pathname ? "JSONRPC" : "HTTP+JSON",
1222
+ };
1223
+ let rpcId: A2ARpcId | null = null;
1224
+ try {
1225
+ // No body read, version parsing, store query or model work before authentication.
1226
+ const p = await principal(request);
1227
+ const publicCard = options.publicCard && path === cardPath && request.method === "GET";
1228
+ if (!p && !publicCard)
1229
+ return Response.json(
1230
+ { error: "Authentication is required." },
1231
+ { status: 401, headers: { "WWW-Authenticate": "Bearer", "cache-control": "no-store" } },
1232
+ );
1233
+ d = { ...d, version: parseA2AVersion(request.headers.get("A2A-Version")) };
1234
+ if (path === cardPath && request.method === "GET") {
1235
+ if (p) await access(scope(p), "AgentCard", undefined, request);
1236
+ return Response.json((await card(d.version)).document, {
1237
+ headers: { Vary: "A2A-Version", "cache-control": "no-store" },
1238
+ });
1239
+ }
1240
+ if (!p) protocol(-32001);
1241
+ const extensions =
1242
+ request.headers
1243
+ .get("A2A-Extensions")
1244
+ ?.split(",")
1245
+ .map((v) => v.trim()) ?? [];
1246
+ if (
1247
+ options.card.extensions?.some(
1248
+ (ext) =>
1249
+ ext.required === true &&
1250
+ (typeof ext.uri !== "string" || !extensions.includes(ext.uri)),
1251
+ )
1252
+ )
1253
+ protocol(-32008);
1254
+ // Empty REST cancellations are valid protocol requests, but still need a JSON media
1255
+ // type here. Otherwise a cross-site form can reach a cookie-authenticated command.
1256
+ const mediaType = request.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
1257
+ if (
1258
+ request.method === "POST" &&
1259
+ mediaType !== "application/json" &&
1260
+ mediaType !== "application/a2a+json"
1261
+ )
1262
+ throw new A2AError("protocol", { code: -32005, status: 415 });
1263
+ let decoded: A2ARequest;
1264
+ if (d.binding === "JSONRPC") {
1265
+ if (request.method !== "POST") throw new A2AError("invalid", { status: 405 });
1266
+ const value = await readA2AJson(request, { limits });
1267
+ // Keep a valid correlation id even when decoding the operation fails.
1268
+ if (
1269
+ value &&
1270
+ typeof value === "object" &&
1271
+ !Array.isArray(value) &&
1272
+ (typeof value.id === "string" || typeof value.id === "number")
1273
+ )
1274
+ rpcId = value.id;
1275
+ const rpc = decodeA2ARpcRequest(value, d.version, limits);
1276
+ rpcId = rpc.id;
1277
+ decoded = rpc.request;
1278
+ } else
1279
+ decoded = await decodeA2AHttpRequest(request, {
1280
+ baseUrl: restUrl.href,
1281
+ version: d.version,
1282
+ tenant: options.tenant,
1283
+ limits,
1284
+ });
1285
+ const result = await operation(scope(p), decoded, request, d, rpcId);
1286
+ if (result instanceof Response) return result;
1287
+ await access(scope(p), decoded.method, undefined, request);
1288
+ const encoded = encodeA2AResult(result, d);
1289
+ return Response.json(
1290
+ d.binding === "JSONRPC" ? { jsonrpc: "2.0", id: rpcId, result: encoded } : encoded,
1291
+ { headers: { "cache-control": "no-store", "A2A-Version": d.version } },
1292
+ );
1293
+ } catch (error) {
1294
+ const encoded = encodeA2AError(
1295
+ error instanceof A2AError
1296
+ ? (error.code ?? (error.kind === "invalid" || error.kind === "limit" ? -32602 : -32603))
1297
+ : -32603,
1298
+ d,
1299
+ rpcId,
1300
+ );
1301
+ return Response.json(encoded.body, {
1302
+ status:
1303
+ error instanceof A2AError && [413, 415, 405].includes(error.status ?? 0)
1304
+ ? error.status
1305
+ : encoded.status,
1306
+ headers: { "cache-control": "no-store" },
1307
+ });
1308
+ }
1309
+ },
1310
+ };
1311
+ }
1312
+
1313
+ /** Gate A2A evidence before handing it to the real host resolver/claim. Does not grant
1314
+ * approvals, invent scopes, consume requests or replace the host's lease checks. */
1315
+ export function a2aPolicy(
1316
+ policy: BackgroundPolicy,
1317
+ options: {
1318
+ tasks: A2ATaskStore;
1319
+ scope: A2ATaskScope;
1320
+ context: BackgroundContext;
1321
+ remoteApprovals?: boolean;
1322
+ remoteClientTools?: boolean;
1323
+ },
1324
+ ): BackgroundPolicy {
1325
+ async function evidence(requestId: string, value: unknown) {
1326
+ if (
1327
+ !isRecord(value) ||
1328
+ value.via !== "a2a" ||
1329
+ value.owner !== options.scope.owner ||
1330
+ value.actorId !== options.scope.actorId ||
1331
+ value.tenant !== options.scope.tenant ||
1332
+ value.taskId !== options.context.runId ||
1333
+ value.requestId !== requestId ||
1334
+ typeof value.messageId !== "string"
1335
+ )
1336
+ throw new A2AError("invalid");
1337
+ const task = await options.tasks.get(options.scope, options.context.runId);
1338
+ const message = task?.messages.find((m) => m.id === value.messageId && m.kind === "resume");
1339
+ if (
1340
+ !message ||
1341
+ message.source !== options.context.continuation?.sourceId ||
1342
+ !equalData(message.answers?.[requestId], value)
1343
+ )
1344
+ throw new A2AError("invalid");
1345
+ return message;
1346
+ }
1347
+ return {
1348
+ ...policy,
1349
+ async claimContinuation(snapshot, continuation) {
1350
+ const messages = new Map<string, A2AMessageReceipt>();
1351
+ for (const [id, value] of Object.entries(continuation.answers)) {
1352
+ if (!isRecord(value) || value.via !== "a2a") continue;
1353
+ const message = await evidence(id, value);
1354
+ if (
1355
+ !Object.entries(message.answers ?? {}).every(([requestId, answer]) =>
1356
+ equalData(continuation.answers[requestId], answer),
1357
+ )
1358
+ )
1359
+ throw new A2AError("invalid");
1360
+ messages.set(message.id, message);
1361
+ }
1362
+ // Scheduled wakes and explicit cancellations are checked by the binding and claimed by
1363
+ // the real host. A cancellation contains no answers and grants no pending request.
1364
+ await policy.claimContinuation(snapshot, continuation);
1365
+ // The host's exact claim and physical segment establish acceptance even if resume's
1366
+ // acknowledgement was lost. A later message may continue, but this one is never replayed.
1367
+ for (const message of messages.values())
1368
+ await receipt(
1369
+ options.tasks,
1370
+ options.scope,
1371
+ options.context.runId,
1372
+ message.id,
1373
+ "accepted",
1374
+ options.context.segmentId,
1375
+ );
1376
+ },
1377
+ async resolveRequest(request, value) {
1378
+ if (!isRecord(value) || value.via !== "a2a") return policy.resolveRequest(request, value);
1379
+ await evidence(request.id, value);
1380
+ if (
1381
+ request.scope.actorId !== options.scope.actorId ||
1382
+ request.scope.expiresAt <= Date.now() ||
1383
+ (request.ask.type === "approval" && !options.remoteApprovals) ||
1384
+ (request.ask.type === "client" && !options.remoteClientTools)
1385
+ )
1386
+ return { type: "pending" };
1387
+ return policy.resolveRequest(request, value);
1388
+ },
1389
+ };
1390
+ }