@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,74 @@
1
+ export { defineRemoteAgent } from "./remote.ts";
2
+ export type {
3
+ RemoteAgent,
4
+ RemoteAgentOptions,
5
+ RemoteInput,
6
+ RemoteJournal,
7
+ RemoteLimits,
8
+ RemoteOutcome,
9
+ RemotePending,
10
+ RemoteReceipt,
11
+ RemoteSend,
12
+ RemoteSnapshot,
13
+ } from "./remote.ts";
14
+ export { createA2AServer, a2aInput, a2aPolicy, A2ATaskRejected } from "./server.ts";
15
+ export type { A2AProjectionContext, A2AServerBase, A2AServerOptions } from "./server.ts";
16
+ export { createMemoryRuns } from "./memory-runs.ts";
17
+ export type { A2ARun, A2ARuns, A2AStoredEvent, MemoryRunsOptions } from "./memory-runs.ts";
18
+ export { createMemoryTaskStore, a2aSegments, A2ATaskConflict } from "./tasks.ts";
19
+ export type {
20
+ A2AMessageReceipt,
21
+ A2APushAttempt,
22
+ A2APushRecord,
23
+ A2ATaskPatch,
24
+ A2ATaskRecord,
25
+ A2ATaskScope,
26
+ A2ATaskStore,
27
+ } from "./tasks.ts";
28
+ export {
29
+ createA2AClient,
30
+ fetchA2AAgentCard,
31
+ readA2AJson,
32
+ decodeA2AHttpRequest,
33
+ encodeA2AHttpRequest,
34
+ } from "./client.ts";
35
+ export type { A2ACallOptions, A2AClient, A2AClientOptions, A2AObservation } from "./client.ts";
36
+ export { checkA2AEndpoint, checkA2ACardEndpoints, selectA2AInterface } from "./policy.ts";
37
+ export type { A2AEndpointPolicy, A2AEndpointUse } from "./policy.ts";
38
+ export { authenticateA2A, bearerToken } from "./auth.ts";
39
+ export type { A2AAuthenticate, A2APrincipal } from "./auth.ts";
40
+ export { signAgentCard, verifyAgentCard, canonicalA2ACard } from "./signing.ts";
41
+ export type { A2ACardSigner } from "./signing.ts";
42
+ export { deliverA2APush, signA2APush, verifyA2APush } from "./push.ts";
43
+ export type { A2APushPolicy } from "./push.ts";
44
+ export {
45
+ A2AError,
46
+ A2A_LIMITS,
47
+ parseA2AVersion,
48
+ parseA2AJson,
49
+ decodeA2AAgentCard,
50
+ decodeA2AEvent,
51
+ decodeA2AMessage,
52
+ decodeA2ARequest,
53
+ decodeA2AResult,
54
+ decodeA2ARpcRequest,
55
+ decodeA2ARpcResponse,
56
+ decodeA2AHttpError,
57
+ decodeA2ATask,
58
+ encodeA2AError,
59
+ encodeA2AEvent,
60
+ encodeA2AMessage,
61
+ encodeA2ARequest,
62
+ encodeA2AResult,
63
+ encodeA2ATask,
64
+ } from "./wire.ts";
65
+ export type * from "./wire.ts";
66
+ export type {
67
+ BackgroundCancelResult,
68
+ BackgroundContext,
69
+ BackgroundContinuationInput,
70
+ BackgroundContinuationResult,
71
+ BackgroundPolicy,
72
+ Continuation,
73
+ SegmentHook,
74
+ } from "../background-types.ts";
@@ -0,0 +1,448 @@
1
+ import { AGENT_RUNTIME, type NodeOutcome } from "../delegation.ts";
2
+ import type {
3
+ BackgroundCancelResult,
4
+ BackgroundContext,
5
+ BackgroundPolicy,
6
+ Continuation,
7
+ SegmentHook,
8
+ } from "../background-types.ts";
9
+ import { checkChildProgress, copyData, equalData, immutableCopy, isId } from "../snapshot.ts";
10
+ import { openRequests, readAnswers, snapshots, untilAbort, wakeAt } from "../tree.ts";
11
+ import { createProgress } from "../progress.ts";
12
+ import { createMemoryInbox, type QueuedInput } from "../steering.ts";
13
+ import type {
14
+ Agent,
15
+ AgentHost,
16
+ AgentInput,
17
+ ResumeOptions,
18
+ RunOptions,
19
+ Session,
20
+ TreeNode,
21
+ } from "../types.ts";
22
+ import type { Workflow } from "../workflow-types.ts";
23
+ import { A2AError } from "./wire.ts";
24
+
25
+ /** Structural public contract. Does not import the optional host run-service peer. */
26
+ export interface A2AStoredEvent {
27
+ seq: number;
28
+ type: string;
29
+ data: unknown;
30
+ }
31
+ export interface A2ARun<T = unknown> {
32
+ id: string;
33
+ status: "queued" | "running" | "succeeded" | "failed" | "cancelled";
34
+ snapshot: TreeNode;
35
+ outcome: NodeOutcome<T> | null;
36
+ wakeAt?: number;
37
+ }
38
+ export interface A2ARuns<I = AgentInput, O = unknown> {
39
+ start(
40
+ owner: string,
41
+ input: I,
42
+ options: { runId: string; sessionId?: string; signal?: AbortSignal },
43
+ ): Promise<{ id: string }>;
44
+ /** Return independent snapshots and hydrated outcomes. A caller or projector must not be
45
+ * able to change stored results by mutating a read. Completed checkpoints are authoritative. */
46
+ read(owner: string, id: string): Promise<A2ARun<O>>;
47
+ observe(
48
+ owner: string,
49
+ id: string,
50
+ afterSeq?: number,
51
+ signal?: AbortSignal,
52
+ ): AsyncIterable<A2AStoredEvent>;
53
+ /** Follow the returned physical segment. Queue acceptance is not a cancelled outcome. */
54
+ cancel(owner: string, id: string): Promise<BackgroundCancelResult>;
55
+ resume(
56
+ owner: string,
57
+ id: string,
58
+ answers: Readonly<Record<string, unknown>>,
59
+ ): Promise<{ id: string }>;
60
+ /** Optional, explicit capability. Enqueue is not a promise that a model consumed the input. */
61
+ send?: (owner: string, id: string, input: QueuedInput) => Promise<void>;
62
+ }
63
+ export interface MemoryRunsOptions {
64
+ /** Required host policy, run again for every physical segment. Claims and authorization are
65
+ * still real host decisions; this binding does not infer approval from evidence or text. */
66
+ policy(context: BackgroundContext): BackgroundPolicy | Promise<BackgroundPolicy>;
67
+ /** Required to track out-of-band segments in the task store. */
68
+ onSegment?: SegmentHook;
69
+ session?: (owner: string, id: string) => Session | Promise<Session>;
70
+ maxSegments?: number;
71
+ maxSnapshotBytes?: number;
72
+ maxEvents?: number;
73
+ maxEventBytes?: number;
74
+ /** Uses the SDK's bounded memory inbox. Without this opt-in, active messages are refused. */
75
+ steering?: boolean;
76
+ }
77
+ interface Row<O> extends A2ARun<O> {
78
+ owner: string;
79
+ continuation?: Continuation;
80
+ controller: AbortController;
81
+ events: A2AStoredEvent[];
82
+ bytes: number;
83
+ seq: number;
84
+ listeners: Set<() => void>;
85
+ settled: Promise<void>;
86
+ }
87
+
88
+ /** Process-local and not crash durable. Composes the real runtime, checkpoint and request
89
+ * claim path. No new agent loop, scheduler or automatic wake. Full stores refuse admissions;
90
+ * dropping this binding drops snapshots, inboxes and continuation claims. */
91
+ export function createMemoryRuns<T>(
92
+ options: MemoryRunsOptions & { agent: Agent<T> },
93
+ ): A2ARuns<AgentInput, T>;
94
+ export function createMemoryRuns<I, O>(
95
+ options: MemoryRunsOptions & { workflow: Workflow<I, O> },
96
+ ): A2ARuns<I, O>;
97
+ export function createMemoryRuns<I, O>(
98
+ options: MemoryRunsOptions & ({ agent: Agent<O> } | { workflow: Workflow<I, O> }),
99
+ ): A2ARuns<I, O> | A2ARuns<AgentInput, O> {
100
+ if ("workflow" in options) {
101
+ const workflow = options.workflow;
102
+ return bindMemory<I, O>(options, {
103
+ open: (input, opts, id) => workflow[AGENT_RUNTIME].open(input, opts, id),
104
+ resume: (snapshot, opts) => workflow.resume(snapshot, opts),
105
+ hydrate: (snapshot) => workflow[AGENT_RUNTIME].hydrate(snapshot),
106
+ });
107
+ }
108
+ const agent = options.agent;
109
+ return bindMemory<AgentInput, O>(options, {
110
+ open: (input, opts, id) => agent[AGENT_RUNTIME].open(input, opts, id),
111
+ resume: (snapshot, opts) => agent.resume(snapshot, opts),
112
+ hydrate: (snapshot) => agent[AGENT_RUNTIME].node.hydrate(snapshot),
113
+ });
114
+ }
115
+ function bindMemory<I, O>(
116
+ options: MemoryRunsOptions,
117
+ runtime: {
118
+ open(input: I, options: RunOptions, runId: string): Promise<TreeNode>;
119
+ resume(snapshot: TreeNode, options: ResumeOptions): Promise<NodeOutcome<O>>;
120
+ hydrate(snapshot: TreeNode): NodeOutcome<O>;
121
+ },
122
+ ): A2ARuns<I, O> {
123
+ const {
124
+ maxSegments = 1000,
125
+ maxSnapshotBytes = 8 * 1024 * 1024,
126
+ maxEvents = 256,
127
+ maxEventBytes = 1024 * 1024,
128
+ } = options;
129
+ if (
130
+ typeof options.policy !== "function" ||
131
+ [maxSegments, maxSnapshotBytes, maxEvents, maxEventBytes].some(
132
+ (n) => !Number.isSafeInteger(n) || n < 1,
133
+ )
134
+ )
135
+ throw new A2AError("invalid");
136
+ const rows = new Map<string, Row<O>>();
137
+ const current = new Map<string, string>();
138
+ const starts = new Set<string>();
139
+ const reserved = new Set<string>();
140
+ const inboxes = new Map<string, ReturnType<typeof createMemoryInbox>>();
141
+ const key = (owner: string, id: string) => JSON.stringify([owner, id]);
142
+ function load(owner: string, id: string): Row<O> {
143
+ const row = rows.get(id);
144
+ if (!row || row.owner !== owner) throw new A2AError("protocol", { code: -32001 });
145
+ return row;
146
+ }
147
+ function checkpoint(row: Row<O>, snapshot: TreeNode) {
148
+ if (new TextEncoder().encode(JSON.stringify(snapshot)).byteLength > maxSnapshotBytes)
149
+ throw new A2AError("limit");
150
+ checkChildProgress(row.snapshot, snapshot);
151
+ row.snapshot = copyData(snapshot);
152
+ }
153
+ function emit(row: Row<O>, type: string, data: unknown) {
154
+ const event = { seq: ++row.seq, type, data: copyData(data) };
155
+ const bytes = new TextEncoder().encode(JSON.stringify(event)).byteLength;
156
+ if (bytes <= maxEventBytes) {
157
+ row.events.push(event);
158
+ row.bytes += bytes;
159
+ }
160
+ while (row.events.length > maxEvents || row.bytes > maxEventBytes) {
161
+ const removed = row.events.shift();
162
+ row.bytes -= new TextEncoder().encode(JSON.stringify(removed)).byteLength;
163
+ }
164
+ for (const wake of row.listeners) wake();
165
+ }
166
+ async function policy(context: BackgroundContext) {
167
+ const trusted = await options.policy(immutableCopy(context));
168
+ for (const name of [
169
+ "authorizeResume",
170
+ "prepareRequest",
171
+ "resolveRequest",
172
+ "beforeTool",
173
+ "claimContinuation",
174
+ ] as const)
175
+ if (typeof trusted?.[name] !== "function") throw new A2AError("invalid");
176
+ return trusted;
177
+ }
178
+ function admission() {
179
+ if (rows.size + reserved.size >= maxSegments) throw new A2AError("limit");
180
+ const id = crypto.randomUUID();
181
+ reserved.add(id);
182
+ return id;
183
+ }
184
+ async function execute(row: Row<O>) {
185
+ const { continuation } = row;
186
+ const initial = copyData(row.snapshot);
187
+ const logical = key(row.owner, initial.runId);
188
+ const progress = createProgress(
189
+ { signal: row.controller.signal, emit: (type, data) => emit(row, type, data) },
190
+ "best-effort",
191
+ );
192
+ try {
193
+ row.status = "running";
194
+ const trusted = await policy({
195
+ owner: row.owner,
196
+ segmentId: row.id,
197
+ runId: initial.runId,
198
+ continuation,
199
+ });
200
+ // These checks are not substitutes for the host's current authorization or claim.
201
+ if (current.get(logical) !== row.id) throw new A2AError("invalid");
202
+ await trusted.authorizeResume(immutableCopy(initial));
203
+ if (
204
+ continuation?.wakeAt !== undefined &&
205
+ (wakeAt(initial) !== continuation.wakeAt || Date.now() < continuation.wakeAt)
206
+ )
207
+ throw new A2AError("invalid");
208
+ if (continuation)
209
+ await trusted.claimContinuation(immutableCopy(initial), immutableCopy(continuation));
210
+ await options.onSegment?.({
211
+ phase: "start",
212
+ signal: row.controller.signal,
213
+ owner: row.owner,
214
+ id: row.id,
215
+ runId: initial.runId,
216
+ state: initial.state,
217
+ snapshot: immutableCopy(initial),
218
+ });
219
+ const session =
220
+ initial.kind === "agent" && initial.session
221
+ ? await options.session?.(row.owner, initial.session.id)
222
+ : undefined;
223
+ if (initial.kind === "agent" && initial.session && session?.id !== initial.session.id)
224
+ throw new A2AError("invalid");
225
+ const host: AgentHost & { authorizeResume: BackgroundPolicy["authorizeResume"] } = {
226
+ ...trusted,
227
+ ...(options.steering ? { inbox: inboxes.get(logical) } : {}),
228
+ progress,
229
+ authorizeResume: async (snapshot) => {
230
+ if (
231
+ current.get(logical) !== row.id ||
232
+ ![...snapshots(row.snapshot)].some((node) => equalData(node, snapshot))
233
+ )
234
+ throw new A2AError("invalid");
235
+ await trusted.authorizeResume(snapshot);
236
+ },
237
+ checkpoint: (snapshot) => checkpoint(row, snapshot),
238
+ };
239
+ const outcome = await runtime.resume(initial, {
240
+ host,
241
+ // Keep the worker lifetime live for claims, checkpoints and hooks. Cancellation is
242
+ // a separate runtime signal, never an answer or a scheduled continuation.
243
+ signal:
244
+ continuation?.kind === "cancel"
245
+ ? AbortSignal.any([row.controller.signal, AbortSignal.abort()])
246
+ : row.controller.signal,
247
+ session,
248
+ answers: continuation?.answers,
249
+ context: trusted.context,
250
+ onEvent: trusted.onEvent,
251
+ onLifecycle: trusted.onLifecycle,
252
+ bindModelProvider: trusted.bindModelProvider,
253
+ });
254
+ checkpoint(row, outcome.snapshot);
255
+ row.outcome = outcome;
256
+ row.status = "succeeded";
257
+ row.wakeAt = wakeAt(outcome.snapshot);
258
+ } catch {
259
+ // Unknown host failure is not a fabricated SDK outcome. Keep the last real checkpoint.
260
+ row.status = row.controller.signal.aborted ? "cancelled" : "failed";
261
+ } finally {
262
+ try {
263
+ await progress.flush();
264
+ } catch {
265
+ /* The real cancellation/outcome remains authoritative. */
266
+ }
267
+ await progress.dispose();
268
+ try {
269
+ await options.onSegment?.({
270
+ phase: "end",
271
+ signal: row.controller.signal,
272
+ owner: row.owner,
273
+ id: row.id,
274
+ runId: row.snapshot.runId,
275
+ state: row.snapshot.state,
276
+ snapshot: immutableCopy(row.snapshot),
277
+ });
278
+ } catch {
279
+ /* End-hook failure must not replace a settled journal or replay its effects. */
280
+ }
281
+ emit(row, "end", { status: row.status });
282
+ if (row.outcome && row.outcome.status !== "suspended") inboxes.delete(logical);
283
+ }
284
+ }
285
+ function launch(owner: string, id: string, snapshot: TreeNode, continuation?: Continuation) {
286
+ const row: Row<O> = {
287
+ owner,
288
+ id,
289
+ continuation,
290
+ snapshot: copyData(snapshot),
291
+ status: "queued",
292
+ outcome: null,
293
+ controller: new AbortController(),
294
+ events: [],
295
+ bytes: 0,
296
+ seq: 0,
297
+ listeners: new Set(),
298
+ settled: Promise.resolve(),
299
+ };
300
+ reserved.delete(id);
301
+ rows.set(id, row);
302
+ current.set(key(owner, snapshot.runId), id);
303
+ row.settled = execute(row);
304
+ return { id };
305
+ }
306
+ return {
307
+ async start(owner, input, start) {
308
+ if (!isId(owner) || !isId(start.runId)) throw new A2AError("invalid");
309
+ const logical = key(owner, start.runId);
310
+ if (starts.has(logical)) throw new A2AError("invalid");
311
+ if (starts.size >= maxSegments) throw new A2AError("limit");
312
+ const id = admission();
313
+ starts.add(logical);
314
+ try {
315
+ start.signal?.throwIfAborted();
316
+ if (start.sessionId !== undefined && !options.session) throw new A2AError("invalid");
317
+ const session =
318
+ start.sessionId && options.session
319
+ ? await options.session(owner, start.sessionId)
320
+ : undefined;
321
+ if (session && session.id !== start.sessionId) throw new A2AError("invalid");
322
+ const snapshot = await runtime.open(input, { session, signal: start.signal }, start.runId);
323
+ start.signal?.throwIfAborted();
324
+ if (options.steering) inboxes.set(logical, createMemoryInbox(start.runId));
325
+ return launch(owner, id, snapshot);
326
+ } catch (error) {
327
+ reserved.delete(id);
328
+ throw error;
329
+ }
330
+ },
331
+ async read(owner, id) {
332
+ const row = load(owner, id);
333
+ // Rehydrate from the real journal, like the durable binding. A validator may return a
334
+ // Date or another non-JSON value; only its candidate is required to be stored as JSON.
335
+ const hydrated = row.outcome ? runtime.hydrate(copyData(row.snapshot)) : null;
336
+ const outcome =
337
+ hydrated && row.outcome && "session" in row.outcome && row.outcome.session
338
+ ? { ...hydrated, session: copyData(row.outcome.session) }
339
+ : hydrated;
340
+ return {
341
+ id,
342
+ status: row.status,
343
+ snapshot: copyData(row.snapshot),
344
+ outcome,
345
+ ...(row.wakeAt === undefined ? {} : { wakeAt: row.wakeAt }),
346
+ };
347
+ },
348
+ async *observe(owner, id, afterSeq = 0, signal) {
349
+ if (!Number.isSafeInteger(afterSeq) || afterSeq < 0) throw new A2AError("invalid");
350
+ const row = load(owner, id);
351
+ let after = afterSeq;
352
+ while (!signal?.aborted) {
353
+ let wake = () => {};
354
+ const changed = new Promise<void>((resolve) => {
355
+ wake = resolve;
356
+ });
357
+ row.listeners.add(wake);
358
+ try {
359
+ const first = row.events[0]?.seq ?? row.seq + 1;
360
+ if (after < first - 1) {
361
+ const dropped = first - after - 1;
362
+ after = first - 1;
363
+ yield { seq: after, type: "agent.gap", data: { dropped, unconfirmed: 0 } };
364
+ }
365
+ const events = row.events.filter((event) => event.seq > after);
366
+ for (const event of events) {
367
+ after = event.seq;
368
+ yield copyData(event);
369
+ }
370
+ if (["succeeded", "failed", "cancelled"].includes(row.status) && after >= row.seq) return;
371
+ if (!events.length) await (signal ? untilAbort(changed, signal) : changed);
372
+ } catch (error) {
373
+ if (!signal?.aborted) throw error;
374
+ } finally {
375
+ row.listeners.delete(wake);
376
+ }
377
+ }
378
+ },
379
+ async cancel(owner, id) {
380
+ const row = load(owner, id);
381
+ const currentId = current.get(key(owner, row.snapshot.runId)) ?? id;
382
+ const active = load(owner, currentId);
383
+ // A second Stop follows the existing command. Aborting its worker would prevent the
384
+ // claimed cancellation from saving its real outcome and running its end hook.
385
+ if (active.continuation?.kind === "cancel") return { id: currentId, requested: true };
386
+ if (currentId !== id) return { id: currentId, requested: false };
387
+ if (row.status === "succeeded" && row.outcome?.status === "suspended") {
388
+ const next = admission();
389
+ launch(owner, next, row.snapshot, {
390
+ id: `cancel/${id}`,
391
+ sourceId: id,
392
+ kind: "cancel",
393
+ answers: {},
394
+ });
395
+ return { id: next, requested: true };
396
+ }
397
+ if (row.status !== "running" && row.status !== "queued") return { id, requested: false };
398
+ row.controller.abort();
399
+ return { id, requested: true };
400
+ },
401
+ async resume(owner, id, evidence) {
402
+ const row = load(owner, id);
403
+ const logical = key(owner, row.snapshot.runId);
404
+ if (
405
+ current.get(logical) !== id ||
406
+ row.status !== "succeeded" ||
407
+ row.outcome?.status !== "suspended"
408
+ )
409
+ throw new A2AError("invalid");
410
+ const answers = readAnswers(row.snapshot, evidence);
411
+ const at = Object.keys(answers).length ? undefined : wakeAt(row.snapshot);
412
+ if (!Object.keys(answers).length && (at === undefined || at > Date.now()))
413
+ throw new A2AError("invalid");
414
+ if (
415
+ openRequests(row.snapshot).some(
416
+ (request) => Object.hasOwn(answers, request.id) && request.scope.expiresAt <= Date.now(),
417
+ )
418
+ )
419
+ throw new A2AError("invalid");
420
+ const next = admission();
421
+ const continuation: Continuation = {
422
+ id: crypto.randomUUID(),
423
+ sourceId: id,
424
+ kind: "answers",
425
+ answers,
426
+ ...(at === undefined ? {} : { wakeAt: at }),
427
+ };
428
+ return launch(owner, next, row.snapshot, continuation);
429
+ },
430
+ ...(options.steering
431
+ ? {
432
+ async send(owner: string, id: string, input: QueuedInput) {
433
+ const row = load(owner, id);
434
+ const logical = key(owner, row.snapshot.runId);
435
+ if (
436
+ current.get(logical) !== id ||
437
+ !["queued", "running"].includes(row.status) ||
438
+ row.snapshot.kind !== "agent"
439
+ )
440
+ throw new A2AError("protocol", { code: -32004 });
441
+ const inbox = inboxes.get(logical);
442
+ if (!inbox) throw new A2AError("protocol", { code: -32004 });
443
+ inbox.enqueue(input);
444
+ },
445
+ }
446
+ : {}),
447
+ };
448
+ }
@@ -0,0 +1,148 @@
1
+ // Endpoint checks adapted from google-adk-js core/src/a2a/agent_card.ts.
2
+ // Copyright 2026 Google LLC. SPDX-License-Identifier: Apache-2.0
3
+ // No DNS lookup or address pinning: those remain the host's responsibility.
4
+ import {
5
+ A2AError,
6
+ type A2AAgentCard,
7
+ type A2ABinding,
8
+ type A2AInterface,
9
+ type A2AVersion,
10
+ } from "./wire.ts";
11
+
12
+ export type A2AEndpointUse = "card" | "rpc" | "push";
13
+ export interface A2AEndpointPolicy {
14
+ /** Host configuration, never peer/model input. Check resolved addresses in an egress proxy or pinned fetch. */
15
+ allow: (url: URL, use: A2AEndpointUse) => boolean | Promise<boolean>;
16
+ allowInsecure?: boolean;
17
+ allowCrossOrigin?: boolean;
18
+ }
19
+
20
+ function ipv6(host: string): number[] | undefined {
21
+ if (!host.startsWith("[")) return undefined;
22
+ const halves = host.slice(1, -1).split("::");
23
+ const left = halves[0] ? halves[0].split(":").map((n) => Number.parseInt(n, 16)) : [];
24
+ const right = halves[1] ? halves[1].split(":").map((n) => Number.parseInt(n, 16)) : [];
25
+ return halves.length === 1
26
+ ? left
27
+ : [...left, ...Array<number>(8 - left.length - right.length).fill(0), ...right];
28
+ }
29
+ function address(host: string): { loopback: boolean; private: boolean; forbidden: boolean } {
30
+ host = host.toLowerCase().replace(/\.$/, "");
31
+ const v6 = ipv6(host);
32
+ let v4 = /^\d+\.\d+\.\d+\.\d+$/.test(host) ? host.split(".").map(Number) : undefined;
33
+ if (v6?.slice(0, 5).every((n) => n === 0) && v6[5] === 0xffff)
34
+ v4 = [v6[6]! >>> 8, v6[6]! & 255, v6[7]! >>> 8, v6[7]! & 255];
35
+ if (v4) {
36
+ const [a, b] = v4;
37
+ return {
38
+ loopback: a === 127,
39
+ private:
40
+ a === 10 ||
41
+ (a === 172 && b! >= 16 && b! <= 31) ||
42
+ (a === 192 && b === 168) ||
43
+ (a === 100 && b! >= 64 && b! <= 127),
44
+ forbidden:
45
+ a === 0 || (a === 169 && b === 254) || a! >= 224 || v4.join(".") === "100.100.100.200",
46
+ };
47
+ }
48
+ if (v6) {
49
+ const local = v6.slice(0, 7).every((n) => n === 0);
50
+ return {
51
+ loopback: local && v6[7] === 1,
52
+ private: (v6[0]! & 0xfe00) === 0xfc00,
53
+ forbidden:
54
+ (v6[0]! & 0xffc0) === 0xfe80 || (v6[0]! & 0xff00) === 0xff00 || (local && v6[7] === 0),
55
+ };
56
+ }
57
+ return {
58
+ loopback: host === "localhost" || host.endsWith(".localhost"),
59
+ private: false,
60
+ forbidden: host === "metadata.google.internal" || host === "metadata.goog",
61
+ };
62
+ }
63
+ function endpoint(value: string): URL {
64
+ try {
65
+ if (value.length > 2048) throw new Error();
66
+ const url = new URL(value);
67
+ if (
68
+ !["https:", "http:"].includes(url.protocol) ||
69
+ url.username ||
70
+ url.password ||
71
+ url.hash ||
72
+ address(url.hostname).forbidden
73
+ )
74
+ throw new Error();
75
+ return url;
76
+ } catch {
77
+ throw new A2AError("endpoint");
78
+ }
79
+ }
80
+ function sameOrigin(a: URL, b: URL): boolean {
81
+ return (
82
+ a.origin === b.origin ||
83
+ (address(a.hostname).loopback &&
84
+ address(b.hostname).loopback &&
85
+ a.protocol === b.protocol &&
86
+ a.port === b.port)
87
+ );
88
+ }
89
+
90
+ /** Literal checks are not a claim about DNS safety. Every destination also needs the host's allow hook. */
91
+ export async function checkA2AEndpoint(
92
+ value: string,
93
+ use: A2AEndpointUse,
94
+ policy: A2AEndpointPolicy,
95
+ cardUrl?: string,
96
+ ): Promise<URL> {
97
+ const url = endpoint(value);
98
+ const host = address(url.hostname);
99
+ if (url.protocol !== "https:" && !host.loopback && !policy?.allowInsecure)
100
+ throw new A2AError("endpoint");
101
+ if (use === "push" && (host.private || host.loopback)) throw new A2AError("endpoint");
102
+ if (use === "rpc" && cardUrl && !policy.allowCrossOrigin && !sameOrigin(endpoint(cardUrl), url))
103
+ throw new A2AError("endpoint");
104
+ let allowed = false;
105
+ try {
106
+ allowed = (await policy?.allow(new URL(url.href), use)) === true;
107
+ } catch {
108
+ /* A policy exception may contain secrets. */
109
+ }
110
+ if (!allowed) throw new A2AError("endpoint");
111
+ return url;
112
+ }
113
+
114
+ export function a2aCardUrl(source: string): string {
115
+ const url = endpoint(source);
116
+ if (!url.pathname.endsWith("/agent-card.json"))
117
+ url.pathname = `${url.pathname.replace(/\/+$/, "")}/.well-known/agent-card.json`;
118
+ return url.href;
119
+ }
120
+
121
+ export async function checkA2ACardEndpoints(
122
+ card: A2AAgentCard,
123
+ source: string,
124
+ policy: A2AEndpointPolicy,
125
+ ): Promise<void> {
126
+ for (const entry of card.interfaces) await checkA2AEndpoint(entry.url, "rpc", policy, source);
127
+ }
128
+
129
+ /** No auto negotiation or fallback: a rejected mutation must not move to another interface. */
130
+ export function selectA2AInterface(
131
+ card: A2AAgentCard,
132
+ version: A2AVersion,
133
+ binding: A2ABinding,
134
+ extensions: readonly string[] = [],
135
+ ): A2AInterface {
136
+ for (const extension of card.capabilities.extensions ?? []) {
137
+ if (extension.required && !extensions.includes(extension.uri))
138
+ throw new A2AError("protocol", { code: -32008 });
139
+ }
140
+ const found = card.interfaces.find(
141
+ (entry) =>
142
+ entry.binding === binding &&
143
+ (entry.version === version ||
144
+ new RegExp(`^${version.replace(".", "\\.")}\\.\\d+$`).test(entry.version)),
145
+ );
146
+ if (!found) throw new A2AError("protocol", { code: -32009 });
147
+ return { ...found };
148
+ }