@botbotgo/agent-harness 0.0.475 → 0.0.476

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 (227) hide show
  1. package/README.md +3 -1234
  2. package/README.zh.md +3 -1191
  3. package/dist/acp.js +1 -1
  4. package/dist/api.js +1 -404
  5. package/dist/benchmark/checkpoint-resume-cost-benchmark.js +1 -55
  6. package/dist/benchmark/deepagent-local-model-benchmark.js +2 -35
  7. package/dist/benchmark/upstream-runtime-ab-benchmark.js +1 -179
  8. package/dist/cli/chat-interactive.js +25 -244
  9. package/dist/cli/chat-rendering.js +6 -100
  10. package/dist/cli/chat-stream.js +23 -512
  11. package/dist/cli/chat-ui.js +21 -199
  12. package/dist/cli/chat-workspace.js +2 -210
  13. package/dist/cli/main.js +21 -428
  14. package/dist/cli/managed-service-commands.js +9 -63
  15. package/dist/cli/managed-service.js +2 -137
  16. package/dist/cli/options-init-chat.js +1 -108
  17. package/dist/cli/options-runtime.js +1 -158
  18. package/dist/cli/options-serve.js +1 -282
  19. package/dist/cli/options.js +2 -19
  20. package/dist/cli/process-guards.js +1 -139
  21. package/dist/cli/request-tree.js +7 -296
  22. package/dist/cli/runtime-commands.js +12 -258
  23. package/dist/cli/runtime-output.js +16 -155
  24. package/dist/cli/server-commands.js +16 -270
  25. package/dist/cli/workspace.js +1 -67
  26. package/dist/cli.js +1 -7
  27. package/dist/client/acp.js +1 -1
  28. package/dist/client/in-process.js +1 -67
  29. package/dist/client/index.js +1 -2
  30. package/dist/client/types.js +0 -1
  31. package/dist/client.js +1 -1
  32. package/dist/contracts/core.js +1 -1
  33. package/dist/contracts/runtime-evaluation.js +0 -1
  34. package/dist/contracts/runtime-memory.js +0 -1
  35. package/dist/contracts/runtime-observability.js +0 -1
  36. package/dist/contracts/runtime-requests.js +0 -1
  37. package/dist/contracts/runtime-scheduling.js +0 -1
  38. package/dist/contracts/runtime.js +1 -27
  39. package/dist/contracts/types.js +1 -3
  40. package/dist/contracts/workspace.js +0 -1
  41. package/dist/flow/build-flow-graph.js +1 -50
  42. package/dist/flow/export-mermaid.js +2 -464
  43. package/dist/flow/export-sequence-mermaid.js +2 -325
  44. package/dist/flow/flow-graph-normalization.js +1 -214
  45. package/dist/flow/flow-graph-runtime.js +1 -107
  46. package/dist/flow/flow-graph-upstream.js +1 -494
  47. package/dist/flow/index.js +1 -3
  48. package/dist/flow/types.js +0 -1
  49. package/dist/index.js +1 -5
  50. package/dist/init-project.js +1 -1
  51. package/dist/knowledge/config.js +1 -32
  52. package/dist/knowledge/contracts.js +0 -1
  53. package/dist/knowledge/index.js +1 -2
  54. package/dist/knowledge/module.js +12 -909
  55. package/dist/knowledge/procedural/config.js +1 -125
  56. package/dist/knowledge/procedural/index.js +1 -2
  57. package/dist/knowledge/procedural/manager.js +9 -345
  58. package/dist/mcp.js +1 -2
  59. package/dist/package-version.d.ts +1 -1
  60. package/dist/package-version.js +1 -2
  61. package/dist/persistence/file-store.js +3 -758
  62. package/dist/persistence/sqlite-request-context-store.js +5 -54
  63. package/dist/persistence/sqlite-request-queue-store.js +10 -108
  64. package/dist/persistence/sqlite-runtime.js +1 -86
  65. package/dist/persistence/sqlite-store.js +62 -810
  66. package/dist/persistence/types.js +0 -1
  67. package/dist/projections/presentation.js +37 -206
  68. package/dist/projections/request-events.js +2 -502
  69. package/dist/projections/upstream-events.js +1 -201
  70. package/dist/protocol/a2a/http-discovery.js +1 -178
  71. package/dist/protocol/a2a/http-rpc.js +6 -622
  72. package/dist/protocol/a2a/http.js +1 -138
  73. package/dist/protocol/a2a/task-state.js +3 -317
  74. package/dist/protocol/acp/client.js +8 -294
  75. package/dist/protocol/acp/harness-client.js +1 -218
  76. package/dist/protocol/acp/http.js +5 -130
  77. package/dist/protocol/acp/server.js +1 -310
  78. package/dist/protocol/acp/stdio.js +2 -69
  79. package/dist/protocol/ag-ui/http.js +3 -378
  80. package/dist/protocol/mcp/server.js +1 -428
  81. package/dist/resource/backend/workspace-scoped-backend.js +1 -319
  82. package/dist/resource/isolation.js +1 -237
  83. package/dist/resource/mcp/tool-support.js +3 -296
  84. package/dist/resource/mcp-tool-support.js +1 -2
  85. package/dist/resource/providers/resource-provider.js +1 -215
  86. package/dist/resource/resource-impl.js +1 -3
  87. package/dist/resource/resource-types.js +0 -1
  88. package/dist/resource/resource.js +1 -1
  89. package/dist/resource/sources.js +1 -247
  90. package/dist/resource/tools/function-tool-resolver.js +2 -272
  91. package/dist/runtime/adapter/compat/deepagent-compat.js +1 -29
  92. package/dist/runtime/adapter/compat/openai-compatible.js +1 -55
  93. package/dist/runtime/adapter/direct-builtin-utility.js +2 -90
  94. package/dist/runtime/adapter/flow/execution-context.js +1 -71
  95. package/dist/runtime/adapter/flow/invocation-flow.js +8 -425
  96. package/dist/runtime/adapter/flow/invoke-runtime.js +1 -20
  97. package/dist/runtime/adapter/flow/stream-runtime.js +11 -1395
  98. package/dist/runtime/adapter/invocation-result.js +2 -473
  99. package/dist/runtime/adapter/local-tool-invocation.js +6 -638
  100. package/dist/runtime/adapter/middleware/context-hygiene.js +1 -83
  101. package/dist/runtime/adapter/middleware-assembly.js +5 -477
  102. package/dist/runtime/adapter/model/invocation-request.js +3 -183
  103. package/dist/runtime/adapter/model/message-assembly.js +1 -28
  104. package/dist/runtime/adapter/model/model-providers.js +23 -1115
  105. package/dist/runtime/adapter/model/prompted-json-tool-call-capture.js +1 -40
  106. package/dist/runtime/adapter/model/prompted-json-tool-policy.js +1 -22
  107. package/dist/runtime/adapter/resilience.js +1 -104
  108. package/dist/runtime/adapter/runtime-adapter-support.js +3 -141
  109. package/dist/runtime/adapter/runtime-shell.js +5 -166
  110. package/dist/runtime/adapter/stream-event-projection.js +2 -622
  111. package/dist/runtime/adapter/stream-text-consumption.js +1 -18
  112. package/dist/runtime/adapter/terminal-status.js +2 -67
  113. package/dist/runtime/adapter/tool/builtin-middleware-tools.js +6 -627
  114. package/dist/runtime/adapter/tool/declared-middleware.js +1 -154
  115. package/dist/runtime/adapter/tool/interrupt-policy.js +1 -34
  116. package/dist/runtime/adapter/tool/provider-tool.js +1 -25
  117. package/dist/runtime/adapter/tool/resolved-tool.js +1 -225
  118. package/dist/runtime/adapter/tool/tool-arguments.js +3 -486
  119. package/dist/runtime/adapter/tool/tool-hitl.js +1 -346
  120. package/dist/runtime/adapter/tool/tool-name-mapping.js +1 -128
  121. package/dist/runtime/adapter/tool/tool-output-artifacts.js +2 -88
  122. package/dist/runtime/adapter/tool/tool-replay.js +1 -37
  123. package/dist/runtime/adapter/tool-resolution.js +1 -86
  124. package/dist/runtime/adapter/upstream-configurable-keys.js +1 -2
  125. package/dist/runtime/agent-runtime-adapter.js +60 -2338
  126. package/dist/runtime/agent-runtime-assembly.js +7 -249
  127. package/dist/runtime/env/runtime-env.js +1 -62
  128. package/dist/runtime/harness/background-runtime.js +1 -8
  129. package/dist/runtime/harness/bindings.js +1 -58
  130. package/dist/runtime/harness/events/event-bus.js +1 -16
  131. package/dist/runtime/harness/events/event-sink.js +1 -61
  132. package/dist/runtime/harness/events/events.js +1 -80
  133. package/dist/runtime/harness/events/listener-runtime.js +1 -13
  134. package/dist/runtime/harness/events/runtime-event-operations.js +1 -9
  135. package/dist/runtime/harness/events/streaming.js +1 -100
  136. package/dist/runtime/harness/events/timeline.js +1 -52
  137. package/dist/runtime/harness/public-shapes.js +1 -186
  138. package/dist/runtime/harness/run/artifact-paths.js +1 -15
  139. package/dist/runtime/harness/run/governance.js +1 -295
  140. package/dist/runtime/harness/run/helpers.js +1 -71
  141. package/dist/runtime/harness/run/inspection.js +1 -409
  142. package/dist/runtime/harness/run/operator-overview.js +1 -80
  143. package/dist/runtime/harness/run/queue-diagnostics.js +1 -15
  144. package/dist/runtime/harness/run/recovery.js +1 -162
  145. package/dist/runtime/harness/run/resources.js +1 -60
  146. package/dist/runtime/harness/run/resume.js +1 -56
  147. package/dist/runtime/harness/run/routing.js +1 -48
  148. package/dist/runtime/harness/run/run-lifecycle.js +1 -66
  149. package/dist/runtime/harness/run/run-operations.js +1 -217
  150. package/dist/runtime/harness/run/run-queue.js +1 -43
  151. package/dist/runtime/harness/run/run-slot-acquisition.js +1 -157
  152. package/dist/runtime/harness/run/session-records.js +1 -97
  153. package/dist/runtime/harness/run/start-run.js +1 -120
  154. package/dist/runtime/harness/run/startup-runtime.js +1 -69
  155. package/dist/runtime/harness/run/stream-run.js +8 -1418
  156. package/dist/runtime/harness/run/surface-semantics.js +1 -79
  157. package/dist/runtime/harness/runtime-defaults.js +1 -39
  158. package/dist/runtime/harness/system/boundary-analysis.js +1 -234
  159. package/dist/runtime/harness/system/health-monitor.js +1 -258
  160. package/dist/runtime/harness/system/inventory.js +1 -129
  161. package/dist/runtime/harness/system/mem0-ingestion-sync.js +5 -345
  162. package/dist/runtime/harness/system/policy-engine.js +1 -175
  163. package/dist/runtime/harness/system/runtime-memory-candidates.js +4 -110
  164. package/dist/runtime/harness/system/runtime-memory-consolidation.js +1 -51
  165. package/dist/runtime/harness/system/runtime-memory-manager.js +10 -693
  166. package/dist/runtime/harness/system/runtime-memory-policy.js +1 -155
  167. package/dist/runtime/harness/system/runtime-memory-records.js +11 -577
  168. package/dist/runtime/harness/system/runtime-memory-sync.js +5 -206
  169. package/dist/runtime/harness/system/session-memory-sync.js +3 -113
  170. package/dist/runtime/harness/system/skill-requirements.js +1 -112
  171. package/dist/runtime/harness/system/store.js +9 -365
  172. package/dist/runtime/harness/tool-gateway/index.js +1 -2
  173. package/dist/runtime/harness/tool-gateway/policy.js +1 -45
  174. package/dist/runtime/harness/tool-gateway/validation.js +1 -176
  175. package/dist/runtime/harness/tool-schema.js +1 -3
  176. package/dist/runtime/harness.js +3 -1490
  177. package/dist/runtime/index.js +1 -3
  178. package/dist/runtime/layout/runtime-layout.js +1 -31
  179. package/dist/runtime/maintenance/checkpoint-maintenance.js +2 -178
  180. package/dist/runtime/maintenance/file-checkpoint-saver.js +1 -106
  181. package/dist/runtime/maintenance/runtime-record-maintenance.js +2 -169
  182. package/dist/runtime/maintenance/sqlite-checkpoint-saver.js +4 -289
  183. package/dist/runtime/parsing/output-content.js +10 -550
  184. package/dist/runtime/parsing/output-parsing.js +1 -4
  185. package/dist/runtime/parsing/output-recovery.js +3 -213
  186. package/dist/runtime/parsing/output-tool-args.js +7 -663
  187. package/dist/runtime/parsing/stream-event-parsing.js +3 -362
  188. package/dist/runtime/prompts/runtime-prompts.js +4 -73
  189. package/dist/runtime/scheduling/system-schedule-manager.js +11 -532
  190. package/dist/runtime/skills/skill-metadata.js +1 -197
  191. package/dist/runtime/startup-tracing.js +2 -37
  192. package/dist/runtime/support/compiled-binding.js +1 -290
  193. package/dist/runtime/support/embedding-models.js +1 -118
  194. package/dist/runtime/support/harness-support.js +5 -137
  195. package/dist/runtime/support/llamaindex.js +1 -108
  196. package/dist/runtime/support/runtime-adapter-options.js +1 -29
  197. package/dist/runtime/support/runtime-factories.js +1 -51
  198. package/dist/runtime/support/vector-stores.js +9 -270
  199. package/dist/scaffold/init-project.js +54 -233
  200. package/dist/tooling/extensions.js +1 -311
  201. package/dist/tooling/module-loader.js +1 -55
  202. package/dist/tools.js +1 -176
  203. package/dist/utils/agent-display.js +1 -18
  204. package/dist/utils/bundled-text.js +4 -39
  205. package/dist/utils/compiled-binding.js +1 -33
  206. package/dist/utils/fs.js +2 -45
  207. package/dist/utils/id.js +1 -9
  208. package/dist/utils/message-content.js +1 -30
  209. package/dist/utils/object.js +1 -6
  210. package/dist/workspace/agent-binding-compiler.js +3 -613
  211. package/dist/workspace/compile.js +1 -472
  212. package/dist/workspace/framework-contract-validation.js +2 -322
  213. package/dist/workspace/index.js +1 -1
  214. package/dist/workspace/object-loader-paths.js +1 -71
  215. package/dist/workspace/object-loader-readers.js +1 -187
  216. package/dist/workspace/object-loader.js +1 -754
  217. package/dist/workspace/resource-compilers.js +1 -374
  218. package/dist/workspace/support/agent-capabilities.js +1 -37
  219. package/dist/workspace/support/agent-execution-config.js +1 -44
  220. package/dist/workspace/support/discovery.js +1 -147
  221. package/dist/workspace/support/source-collectors.js +1 -30
  222. package/dist/workspace/support/source-protocols.js +2 -192
  223. package/dist/workspace/support/workspace-ref-utils.js +1 -362
  224. package/dist/workspace/tool-hydration.js +1 -280
  225. package/dist/workspace/validate.js +1 -99
  226. package/dist/workspace/yaml-object-reader.js +1 -285
  227. package/package.json +7 -3
@@ -1,622 +1,6 @@
1
- import { acceptsSse, buildAgentCard, buildExtendedAgentCard, writeJson, writeOptionalAgentCardIntegrityHeaders, } from "./http-discovery.js";
2
- import { buildTaskFromRuntime, buildTaskFromSessionAndRequest, clonePushNotificationConfig, fingerprintTaskForPush, hydrateTaskStateFromEvents, isTerminalTaskState, isV1Method, listTasksFromRuntime, toRequestRecord, toSendMessageResult, toSessionRecord, toStreamingResult, withRunResult, withStreamingStatusText, } from "./task-state.js";
3
- function writeSseHeaders(response) {
4
- response.statusCode = 200;
5
- response.setHeader("content-type", "text/event-stream; charset=utf-8");
6
- response.setHeader("cache-control", "no-cache, no-transform");
7
- response.setHeader("connection", "keep-alive");
8
- }
9
- function writeSseEvent(response, event, payload) {
10
- return new Promise((resolve, reject) => {
11
- response.write(`event: ${event}\ndata: ${JSON.stringify(payload)}\n\n`, (error) => {
12
- if (error) {
13
- reject(error);
14
- return;
15
- }
16
- resolve();
17
- });
18
- });
19
- }
20
- export function toError(id, code, message, data) {
21
- return {
22
- jsonrpc: "2.0",
23
- id,
24
- error: {
25
- code,
26
- message,
27
- ...(data === undefined ? {} : { data }),
28
- },
29
- };
30
- }
31
- function toSuccess(id, result) {
32
- return {
33
- jsonrpc: "2.0",
34
- id,
35
- result,
36
- };
37
- }
38
- export function readRequestBody(request) {
39
- return new Promise((resolve, reject) => {
40
- const chunks = [];
41
- request.on("data", (chunk) => {
42
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
43
- });
44
- request.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
45
- request.on("error", reject);
46
- });
47
- }
48
- function parseTextPart(part) {
49
- if (!part || typeof part !== "object" || Array.isArray(part)) {
50
- return null;
51
- }
52
- const typed = part;
53
- if (typeof typed.text !== "string"
54
- || typed.text.trim().length === 0
55
- || (typed.type !== undefined && typed.type !== "text")) {
56
- return null;
57
- }
58
- return typed.text;
59
- }
60
- function normalizeUserRole(role) {
61
- return typeof role === "string" ? role.toLowerCase().replace(/^role_/, "") : "";
62
- }
63
- function parsePushNotificationAuthenticationInfo(value) {
64
- if (!value || typeof value !== "object" || Array.isArray(value)) {
65
- return undefined;
66
- }
67
- const typed = value;
68
- const schemes = Array.isArray(typed.schemes)
69
- ? typed.schemes
70
- .filter((entry) => typeof entry === "string" && entry.trim().length > 0)
71
- .map((entry) => entry.trim())
72
- : [];
73
- if (schemes.length === 0) {
74
- return undefined;
75
- }
76
- return {
77
- schemes,
78
- ...(typeof typed.credentials === "string" && typed.credentials.trim().length > 0
79
- ? { credentials: typed.credentials.trim() }
80
- : {}),
81
- };
82
- }
83
- function parsePendingPushNotificationConfig(value) {
84
- if (!value || typeof value !== "object" || Array.isArray(value)) {
85
- return undefined;
86
- }
87
- const typed = value;
88
- const rawUrl = typeof typed.url === "string" ? typed.url.trim() : "";
89
- if (rawUrl.length === 0) {
90
- throw new Error("A2A push notification config requires `url`.");
91
- }
92
- const parsedUrl = new URL(rawUrl);
93
- if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
94
- throw new Error("A2A push notification config requires an http or https URL.");
95
- }
96
- const authentication = parsePushNotificationAuthenticationInfo(typed.authentication);
97
- return {
98
- url: parsedUrl.toString(),
99
- ...(typeof typed.id === "string" && typed.id.trim().length > 0 ? { id: typed.id.trim() } : {}),
100
- ...(typeof typed.token === "string" && typed.token.trim().length > 0 ? { token: typed.token.trim() } : {}),
101
- ...(authentication ? { authentication } : {}),
102
- };
103
- }
104
- function parseMessageSendParams(params) {
105
- if (!params || typeof params !== "object" || Array.isArray(params)) {
106
- throw new Error("A2A message/send requires params object.");
107
- }
108
- const typed = params;
109
- const message = typed.message;
110
- if (!message || typeof message !== "object" || Array.isArray(message)) {
111
- throw new Error("A2A message/send requires `message`.");
112
- }
113
- const typedMessage = message;
114
- const role = normalizeUserRole(typedMessage.role);
115
- if (role !== "user") {
116
- throw new Error("A2A message/send currently supports only `user` / `ROLE_USER` role messages.");
117
- }
118
- const parts = Array.isArray(typedMessage.parts) ? typedMessage.parts : [];
119
- const textParts = parts.map(parseTextPart).filter((item) => Boolean(item));
120
- if (textParts.length === 0) {
121
- throw new Error("A2A message/send requires at least one text part.");
122
- }
123
- const sessionId = typeof typed.contextId === "string" && typed.contextId.trim().length > 0
124
- ? typed.contextId.trim()
125
- : typeof typedMessage.contextId === "string" && typedMessage.contextId.trim().length > 0
126
- ? typedMessage.contextId.trim()
127
- : undefined;
128
- const agentId = typeof typed.agentId === "string" && typed.agentId.trim().length > 0
129
- ? typed.agentId.trim()
130
- : undefined;
131
- const metadata = typed.metadata;
132
- const invocation = metadata && typeof metadata === "object" && !Array.isArray(metadata)
133
- ? metadata
134
- : undefined;
135
- const configuration = typed.configuration;
136
- const nestedPushNotificationConfig = configuration && typeof configuration === "object" && !Array.isArray(configuration)
137
- ? configuration.pushNotificationConfig
138
- ?? configuration.taskPushNotificationConfig
139
- : undefined;
140
- const pushNotificationConfig = parsePendingPushNotificationConfig(typed.pushNotificationConfig ?? nestedPushNotificationConfig);
141
- return {
142
- input: textParts.join("\n\n"),
143
- ...(agentId ? { agentId } : {}),
144
- ...(sessionId ? { sessionId } : {}),
145
- ...(invocation ? { invocation } : {}),
146
- ...(pushNotificationConfig ? { pushNotificationConfig } : {}),
147
- };
148
- }
149
- function attachServiceParameters(invocation, serviceParameters) {
150
- return {
151
- ...(invocation ?? {}),
152
- protocol: {
153
- ...(invocation?.protocol && typeof invocation.protocol === "object" && !Array.isArray(invocation.protocol)
154
- ? invocation.protocol
155
- : {}),
156
- a2a: {
157
- version: serviceParameters.version,
158
- ...(serviceParameters.extensions.length > 0 ? { extensions: serviceParameters.extensions } : {}),
159
- },
160
- },
161
- };
162
- }
163
- function parseTaskLocatorParams(params) {
164
- if (!params || typeof params !== "object" || Array.isArray(params)) {
165
- throw new Error("A2A task lookup requires params object.");
166
- }
167
- const typed = params;
168
- const taskId = typeof typed.id === "string" && typed.id.trim().length > 0
169
- ? typed.id.trim()
170
- : typeof typed.taskId === "string" && typed.taskId.trim().length > 0
171
- ? typed.taskId.trim()
172
- : "";
173
- if (!taskId) {
174
- throw new Error("A2A task lookup requires `id`.");
175
- }
176
- return { taskId };
177
- }
178
- function parseTaskListParams(params) {
179
- if (!params || typeof params !== "object" || Array.isArray(params)) {
180
- return { limit: 20 };
181
- }
182
- const typed = params;
183
- const rawLimit = typeof typed.pageSize === "number" && Number.isFinite(typed.pageSize)
184
- ? typed.pageSize
185
- : typeof typed.limit === "number" && Number.isFinite(typed.limit)
186
- ? typed.limit
187
- : 20;
188
- const limitValue = typeof rawLimit === "number" && Number.isFinite(rawLimit)
189
- ? Math.max(1, Math.min(100, Math.trunc(rawLimit)))
190
- : 20;
191
- return {
192
- ...(typeof typed.agentId === "string" && typed.agentId.trim().length > 0 ? { agentId: typed.agentId.trim() } : {}),
193
- ...(typeof typed.contextId === "string" && typed.contextId.trim().length > 0 ? { contextId: typed.contextId.trim() } : {}),
194
- ...(typeof typed.status === "string" && typed.status.trim().length > 0
195
- ? { state: typed.status.trim() }
196
- : typeof typed.state === "string" && typed.state.trim().length > 0
197
- ? { state: typed.state.trim() }
198
- : {}),
199
- ...(typeof typed.pageToken === "string" && typed.pageToken.trim().length > 0
200
- ? { cursor: typed.pageToken.trim() }
201
- : typeof typed.cursor === "string" && typed.cursor.trim().length > 0
202
- ? { cursor: typed.cursor.trim() }
203
- : {}),
204
- limit: limitValue,
205
- };
206
- }
207
- function parsePushNotificationLocatorParams(params) {
208
- if (!params || typeof params !== "object" || Array.isArray(params)) {
209
- throw new Error("A2A push notification lookup requires params object.");
210
- }
211
- const typed = params;
212
- const taskId = typeof typed.taskId === "string" && typed.taskId.trim().length > 0 ? typed.taskId.trim() : "";
213
- const configId = typeof typed.id === "string" && typed.id.trim().length > 0 ? typed.id.trim() : "";
214
- if (!taskId) {
215
- throw new Error("A2A push notification lookup requires `taskId`.");
216
- }
217
- if (!configId) {
218
- throw new Error("A2A push notification lookup requires `id`.");
219
- }
220
- return { taskId, configId };
221
- }
222
- function parsePushNotificationListParams(params) {
223
- if (!params || typeof params !== "object" || Array.isArray(params)) {
224
- throw new Error("A2A push notification list requires params object.");
225
- }
226
- const typed = params;
227
- const taskId = typeof typed.taskId === "string" && typed.taskId.trim().length > 0 ? typed.taskId.trim() : "";
228
- if (!taskId) {
229
- throw new Error("A2A push notification list requires `taskId`.");
230
- }
231
- const pageSize = typeof typed.pageSize === "number" && Number.isFinite(typed.pageSize)
232
- ? Math.max(1, Math.min(100, Math.trunc(typed.pageSize)))
233
- : 20;
234
- return {
235
- taskId,
236
- pageSize,
237
- ...(typeof typed.pageToken === "string" && typed.pageToken.trim().length > 0 ? { pageToken: typed.pageToken.trim() } : {}),
238
- };
239
- }
240
- function parseCreatePushNotificationConfigParams(params) {
241
- if (!params || typeof params !== "object" || Array.isArray(params)) {
242
- throw new Error("A2A push notification create requires params object.");
243
- }
244
- const typed = params;
245
- const taskId = typeof typed.taskId === "string" && typed.taskId.trim().length > 0 ? typed.taskId.trim() : "";
246
- if (!taskId) {
247
- throw new Error("A2A push notification create requires `taskId`.");
248
- }
249
- const config = parsePendingPushNotificationConfig(typed.pushNotificationConfig ?? typed.config ?? typed);
250
- if (!config) {
251
- throw new Error("A2A push notification create requires a config object.");
252
- }
253
- return { taskId, config };
254
- }
255
- async function sendPushNotification(config, task) {
256
- const headers = { "content-type": "application/json" };
257
- if (config.token) {
258
- headers["x-a2a-notification-token"] = config.token;
259
- }
260
- const scheme = config.authentication?.schemes[0]?.toLowerCase();
261
- if (scheme === "bearer" && config.authentication?.credentials) {
262
- headers.authorization = `Bearer ${config.authentication.credentials}`;
263
- }
264
- else if (scheme === "basic" && config.authentication?.credentials) {
265
- headers.authorization = `Basic ${config.authentication.credentials}`;
266
- }
267
- await fetch(config.url, {
268
- method: "POST",
269
- headers,
270
- body: JSON.stringify({ task }),
271
- });
272
- }
273
- async function streamTaskUpdates(response, id, method, iterator) {
274
- writeSseHeaders(response);
275
- for await (const item of iterator) {
276
- if (!item.task) {
277
- continue;
278
- }
279
- await writeSseEvent(response, "task-update", toSuccess(id, toStreamingResult(method, item.task, item.mode)));
280
- }
281
- response.end();
282
- }
283
- async function* streamSendMessageTaskUpdates(runtime, options, method) {
284
- let requestId;
285
- let streamedText = "";
286
- let emittedInitialTask = false;
287
- for await (const item of runtime.streamEvents(options)) {
288
- if (item.type === "event") {
289
- requestId = requestId ?? item.event.requestId;
290
- if (item.event.eventType === "output.delta" && typeof item.event.payload.content === "string") {
291
- streamedText += item.event.payload.content;
292
- }
293
- if (item.event.eventType === "request.created"
294
- || item.event.eventType === "request.state.changed"
295
- || item.event.eventType === "output.delta"
296
- || item.event.eventType === "approval.requested") {
297
- const task = withStreamingStatusText(await buildTaskFromRuntime(runtime, item.event.requestId), streamedText || undefined);
298
- if (task) {
299
- yield { task, mode: emittedInitialTask ? "status-update" : "task" };
300
- emittedInitialTask = true;
301
- }
302
- }
303
- continue;
304
- }
305
- if (item.type === "result") {
306
- const task = withRunResult(await buildTaskFromRuntime(runtime, item.result.requestId), item.result, streamedText || item.result.output);
307
- yield { task, mode: emittedInitialTask ? "status-update" : "task" };
308
- return;
309
- }
310
- if (item.type === "upstream-event" && requestId) {
311
- const task = withStreamingStatusText(await buildTaskFromRuntime(runtime, requestId), streamedText || undefined);
312
- if (task) {
313
- yield { task, mode: emittedInitialTask ? "status-update" : "task" };
314
- emittedInitialTask = true;
315
- }
316
- }
317
- }
318
- }
319
- async function streamExistingTaskUpdates(runtime, response, id, method, taskId) {
320
- writeSseHeaders(response);
321
- let currentTask = await hydrateTaskStateFromEvents(runtime, await buildTaskFromRuntime(runtime, taskId));
322
- if (!currentTask) {
323
- await writeSseEvent(response, "error", toError(id, -32001, "Task not found."));
324
- response.end();
325
- return;
326
- }
327
- await writeSseEvent(response, "task-update", toSuccess(id, toStreamingResult(method, currentTask, "task")));
328
- if (isTerminalTaskState(currentTask.status.state)) {
329
- response.end();
330
- return;
331
- }
332
- await new Promise((resolve) => {
333
- let closed = false;
334
- let idleTimer;
335
- let lastFingerprint = JSON.stringify({
336
- state: currentTask?.status.state,
337
- message: currentTask?.status.message,
338
- });
339
- const armIdleTimer = () => {
340
- if (idleTimer) {
341
- clearTimeout(idleTimer);
342
- }
343
- idleTimer = setTimeout(() => {
344
- response.end();
345
- finish();
346
- }, 1_000);
347
- };
348
- const finish = () => {
349
- if (closed) {
350
- return;
351
- }
352
- closed = true;
353
- unsubscribe();
354
- clearInterval(pollTimer);
355
- if (idleTimer) {
356
- clearTimeout(idleTimer);
357
- }
358
- resolve();
359
- };
360
- const emitLatestTask = async () => {
361
- currentTask = await hydrateTaskStateFromEvents(runtime, await buildTaskFromRuntime(runtime, taskId));
362
- if (!currentTask) {
363
- await writeSseEvent(response, "error", toError(id, -32001, "Task not found."));
364
- response.end();
365
- finish();
366
- return;
367
- }
368
- const fingerprint = JSON.stringify({
369
- state: currentTask.status.state,
370
- message: currentTask.status.message,
371
- });
372
- if (fingerprint !== lastFingerprint) {
373
- lastFingerprint = fingerprint;
374
- await writeSseEvent(response, "task-update", toSuccess(id, toStreamingResult(method, currentTask, isV1Method(method) ? "status-update" : "task")));
375
- armIdleTimer();
376
- }
377
- if (isTerminalTaskState(currentTask.status.state)) {
378
- response.end();
379
- finish();
380
- }
381
- };
382
- const unsubscribe = runtime.subscribe((event) => {
383
- if (event.requestId !== taskId) {
384
- return;
385
- }
386
- if (event.eventType !== "request.state.changed"
387
- && event.eventType !== "output.delta"
388
- && event.eventType !== "approval.requested"
389
- && event.eventType !== "approval.resolved") {
390
- return;
391
- }
392
- void emitLatestTask();
393
- });
394
- const pollTimer = setInterval(() => {
395
- void emitLatestTask();
396
- }, 250);
397
- armIdleTimer();
398
- response.on("close", finish);
399
- });
400
- }
401
- export function createPushNotificationRegistry(runtime, createId) {
402
- const pushConfigsByTask = new Map();
403
- const register = (taskId, config) => {
404
- const entry = {
405
- id: config.id ?? `push-${createId()}`,
406
- taskId,
407
- url: config.url,
408
- ...(config.token ? { token: config.token } : {}),
409
- ...(config.authentication ? { authentication: config.authentication } : {}),
410
- };
411
- let taskConfigs = pushConfigsByTask.get(taskId);
412
- if (!taskConfigs) {
413
- taskConfigs = new Map();
414
- pushConfigsByTask.set(taskId, taskConfigs);
415
- }
416
- taskConfigs.set(entry.id, entry);
417
- return entry;
418
- };
419
- const list = (taskId) => [...(pushConfigsByTask.get(taskId)?.values() ?? [])].sort((left, right) => left.id.localeCompare(right.id));
420
- const get = (taskId, configId) => pushConfigsByTask.get(taskId)?.get(configId);
421
- const remove = (taskId, configId) => {
422
- const taskConfigs = pushConfigsByTask.get(taskId);
423
- if (!taskConfigs) {
424
- return false;
425
- }
426
- const deleted = taskConfigs.delete(configId);
427
- if (taskConfigs.size === 0) {
428
- pushConfigsByTask.delete(taskId);
429
- }
430
- return deleted;
431
- };
432
- const dispatch = async (taskId) => {
433
- const task = await hydrateTaskStateFromEvents(runtime, await buildTaskFromRuntime(runtime, taskId));
434
- if (!task) {
435
- return;
436
- }
437
- const fingerprint = fingerprintTaskForPush(task);
438
- const configs = list(taskId);
439
- await Promise.all(configs.map(async (config) => {
440
- if (config.lastFingerprint === fingerprint) {
441
- return;
442
- }
443
- try {
444
- await sendPushNotification(config, task);
445
- config.lastFingerprint = fingerprint;
446
- }
447
- catch {
448
- // Push delivery is best-effort and should not fail the transport request.
449
- }
450
- }));
451
- };
452
- const pushRelevantEventTypes = new Set([
453
- "request.state.changed",
454
- "approval.requested",
455
- "approval.resolved",
456
- ]);
457
- const unsubscribe = runtime.subscribe((event) => {
458
- if (!pushRelevantEventTypes.has(event.eventType) || !pushConfigsByTask.has(event.requestId)) {
459
- return;
460
- }
461
- void dispatch(event.requestId);
462
- });
463
- return { register, list, get, delete: remove, dispatch, unsubscribe };
464
- }
465
- export async function handleA2aJsonRpcRequest(input) {
466
- const { runtime, request, response, payload, serviceParameters, serverOptions, buildCardOptions, pushNotifications } = input;
467
- if (payload.method === "message/send" || payload.method === "tasks/send" || payload.method === "SendMessage") {
468
- const parsed = parseMessageSendParams(payload.params);
469
- const result = await runtime.run({
470
- agentId: parsed.agentId ?? serverOptions.defaultAgentId,
471
- input: parsed.input,
472
- ...(parsed.sessionId ? { sessionId: parsed.sessionId } : {}),
473
- invocation: attachServiceParameters(parsed.invocation, serviceParameters),
474
- });
475
- const session = await runtime.getSessionRecord(result.sessionId);
476
- const requestRecord = await runtime.getRequest(result.requestId);
477
- const approvals = await runtime.listApprovals({ sessionId: result.sessionId, requestId: result.requestId });
478
- const task = buildTaskFromSessionAndRequest(toSessionRecord(session), toRequestRecord(requestRecord), approvals, result.output);
479
- if (task && parsed.pushNotificationConfig) {
480
- pushNotifications.register(task.id, parsed.pushNotificationConfig);
481
- await pushNotifications.dispatch(task.id);
482
- }
483
- writeJson(response, 200, toSuccess(payload.id ?? null, toSendMessageResult(payload.method, task)));
484
- return;
485
- }
486
- if (payload.method === "GetAgentCard") {
487
- writeOptionalAgentCardIntegrityHeaders(response, {
488
- registryUrls: serverOptions.registryUrls,
489
- agentCardSignature: serverOptions.agentCardSignature,
490
- });
491
- writeJson(response, 200, toSuccess(payload.id ?? null, buildAgentCard(runtime, buildCardOptions())));
492
- return;
493
- }
494
- if (payload.method === "message/stream" || payload.method === "SendStreamingMessage") {
495
- if (!acceptsSse(request)) {
496
- writeJson(response, 406, toError(payload.id ?? null, -32004, "A2A streaming requires `Accept: text/event-stream`."));
497
- return;
498
- }
499
- const parsed = parseMessageSendParams(payload.params);
500
- let registeredPushTaskId;
501
- const sourceIterator = streamSendMessageTaskUpdates(runtime, {
502
- agentId: parsed.agentId ?? serverOptions.defaultAgentId,
503
- input: parsed.input,
504
- ...(parsed.sessionId ? { sessionId: parsed.sessionId } : {}),
505
- invocation: attachServiceParameters(parsed.invocation, serviceParameters),
506
- }, payload.method);
507
- const iterator = (async function* () {
508
- for await (const item of sourceIterator) {
509
- if (item.task && parsed.pushNotificationConfig && !registeredPushTaskId) {
510
- registeredPushTaskId = item.task.id;
511
- pushNotifications.register(item.task.id, parsed.pushNotificationConfig);
512
- await pushNotifications.dispatch(item.task.id);
513
- }
514
- yield item;
515
- }
516
- }());
517
- await streamTaskUpdates(response, payload.id ?? null, payload.method, iterator);
518
- return;
519
- }
520
- if (payload.method === "tasks/get" || payload.method === "GetTask") {
521
- const { taskId } = parseTaskLocatorParams(payload.params);
522
- const task = await buildTaskFromRuntime(runtime, taskId);
523
- if (!task) {
524
- writeJson(response, 200, toError(payload.id ?? null, -32001, "Task not found."));
525
- return;
526
- }
527
- writeJson(response, 200, toSuccess(payload.id ?? null, task));
528
- return;
529
- }
530
- if (payload.method === "tasks/list" || payload.method === "ListTasks") {
531
- const taskList = await listTasksFromRuntime(runtime, parseTaskListParams(payload.params));
532
- writeJson(response, 200, toSuccess(payload.id ?? null, taskList));
533
- return;
534
- }
535
- if (payload.method === "tasks/cancel" || payload.method === "CancelTask") {
536
- const { taskId } = parseTaskLocatorParams(payload.params);
537
- const result = await runtime.cancelRequest({ requestId: taskId, reason: "Cancelled via A2A bridge." });
538
- const task = await buildTaskFromRuntime(runtime, result.requestId);
539
- writeJson(response, 200, toSuccess(payload.id ?? null, task));
540
- return;
541
- }
542
- if (payload.method === "tasks/subscribe" || payload.method === "SubscribeToTask") {
543
- const { taskId } = parseTaskLocatorParams(payload.params);
544
- const task = await buildTaskFromRuntime(runtime, taskId);
545
- if (!task) {
546
- writeJson(response, 200, toError(payload.id ?? null, -32001, "Task not found."));
547
- return;
548
- }
549
- if (payload.method === "SubscribeToTask") {
550
- if (isTerminalTaskState(task.status.state)) {
551
- writeJson(response, 200, toError(payload.id ?? null, -32004, "SubscribeToTask is not supported for tasks in terminal state."));
552
- return;
553
- }
554
- if (!acceptsSse(request)) {
555
- writeJson(response, 406, toError(payload.id ?? null, -32004, "A2A streaming subscriptions require `Accept: text/event-stream`."));
556
- return;
557
- }
558
- await streamExistingTaskUpdates(runtime, response, payload.id ?? null, payload.method, taskId);
559
- return;
560
- }
561
- writeJson(response, 200, toSuccess(payload.id ?? null, {
562
- task,
563
- streamable: false,
564
- pushNotifications: true,
565
- nextPollAfterMs: isTerminalTaskState(task.status.state) ? 0 : 1_000,
566
- }));
567
- return;
568
- }
569
- if (payload.method === "CreateTaskPushNotificationConfig") {
570
- const { taskId, config } = parseCreatePushNotificationConfigParams(payload.params);
571
- if (!await buildTaskFromRuntime(runtime, taskId)) {
572
- writeJson(response, 200, toError(payload.id ?? null, -32001, "Task not found."));
573
- return;
574
- }
575
- const created = pushNotifications.register(taskId, config);
576
- await pushNotifications.dispatch(taskId);
577
- writeJson(response, 200, toSuccess(payload.id ?? null, clonePushNotificationConfig(created)));
578
- return;
579
- }
580
- if (payload.method === "GetTaskPushNotificationConfig") {
581
- const { taskId, configId } = parsePushNotificationLocatorParams(payload.params);
582
- const config = pushNotifications.get(taskId, configId);
583
- if (!config) {
584
- writeJson(response, 200, toError(payload.id ?? null, -32001, "Push notification config not found."));
585
- return;
586
- }
587
- writeJson(response, 200, toSuccess(payload.id ?? null, clonePushNotificationConfig(config)));
588
- return;
589
- }
590
- if (payload.method === "ListTaskPushNotificationConfigs") {
591
- const { taskId, pageSize, pageToken } = parsePushNotificationListParams(payload.params);
592
- const configs = pushNotifications.list(taskId);
593
- const startIndex = pageToken ? Number.parseInt(Buffer.from(pageToken, "base64url").toString("utf8"), 10) || 0 : 0;
594
- const page = configs.slice(startIndex, startIndex + pageSize).map(clonePushNotificationConfig);
595
- const nextIndex = startIndex + page.length;
596
- const nextPageToken = nextIndex < configs.length ? Buffer.from(String(nextIndex), "utf8").toString("base64url") : "";
597
- const result = {
598
- configs: page,
599
- nextPageToken,
600
- };
601
- writeJson(response, 200, toSuccess(payload.id ?? null, result));
602
- return;
603
- }
604
- if (payload.method === "DeleteTaskPushNotificationConfig") {
605
- const { taskId, configId } = parsePushNotificationLocatorParams(payload.params);
606
- if (!pushNotifications.delete(taskId, configId)) {
607
- writeJson(response, 200, toError(payload.id ?? null, -32001, "Push notification config not found."));
608
- return;
609
- }
610
- writeJson(response, 200, toSuccess(payload.id ?? null, { deleted: true, id: configId, taskId }));
611
- return;
612
- }
613
- if (payload.method === "GetExtendedAgentCard") {
614
- writeOptionalAgentCardIntegrityHeaders(response, {
615
- registryUrls: serverOptions.registryUrls,
616
- agentCardSignature: serverOptions.agentCardSignature,
617
- });
618
- writeJson(response, 200, toSuccess(payload.id ?? null, buildExtendedAgentCard(runtime, buildCardOptions())));
619
- return;
620
- }
621
- writeJson(response, 200, toError(payload.id ?? null, -32601, `Unknown A2A method: ${payload.method}`));
622
- }
1
+ import{acceptsSse as v,buildAgentCard as U,buildExtendedAgentCard as z,writeJson as p,writeOptionalAgentCardIntegrityHeaders as x}from"./http-discovery.js";import{buildTaskFromRuntime as w,buildTaskFromSessionAndRequest as F,clonePushNotificationConfig as T,fingerprintTaskForPush as B,hydrateTaskStateFromEvents as b,isTerminalTaskState as I,isV1Method as O,listTasksFromRuntime as J,toRequestRecord as $,toSendMessageResult as H,toSessionRecord as G,toStreamingResult as S,withRunResult as _,withStreamingStatusText as C}from"./task-state.js";function P(e){e.statusCode=200,e.setHeader("content-type","text/event-stream; charset=utf-8"),e.setHeader("cache-control","no-cache, no-transform"),e.setHeader("connection","keep-alive")}function A(e,t,s){return new Promise((i,n)=>{e.write(`event: ${t}
2
+ data: ${JSON.stringify(s)}
3
+
4
+ `,c=>{if(c){n(c);return}i()})})}function k(e,t,s,i){return{jsonrpc:"2.0",id:e,error:{code:t,message:s,...i===void 0?{}:{data:i}}}}function h(e,t){return{jsonrpc:"2.0",id:e,result:t}}function st(e){return new Promise((t,s)=>{const i=[];e.on("data",n=>{i.push(Buffer.isBuffer(n)?n:Buffer.from(n))}),e.on("end",()=>t(Buffer.concat(i).toString("utf8"))),e.on("error",s)})}function V(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return typeof t.text!="string"||t.text.trim().length===0||t.type!==void 0&&t.type!=="text"?null:t.text}function D(e){return typeof e=="string"?e.toLowerCase().replace(/^role_/,""):""}function K(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,s=Array.isArray(t.schemes)?t.schemes.filter(i=>typeof i=="string"&&i.trim().length>0).map(i=>i.trim()):[];if(s.length!==0)return{schemes:s,...typeof t.credentials=="string"&&t.credentials.trim().length>0?{credentials:t.credentials.trim()}:{}}}function N(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,s=typeof t.url=="string"?t.url.trim():"";if(s.length===0)throw new Error("A2A push notification config requires `url`.");const i=new URL(s);if(i.protocol!=="http:"&&i.protocol!=="https:")throw new Error("A2A push notification config requires an http or https URL.");const n=K(t.authentication);return{url:i.toString(),...typeof t.id=="string"&&t.id.trim().length>0?{id:t.id.trim()}:{},...typeof t.token=="string"&&t.token.trim().length>0?{token:t.token.trim()}:{},...n?{authentication:n}:{}}}function E(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("A2A message/send requires params object.");const t=e,s=t.message;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("A2A message/send requires `message`.");const i=s;if(D(i.role)!=="user")throw new Error("A2A message/send currently supports only `user` / `ROLE_USER` role messages.");const u=(Array.isArray(i.parts)?i.parts:[]).map(V).filter(m=>!!m);if(u.length===0)throw new Error("A2A message/send requires at least one text part.");const g=typeof t.contextId=="string"&&t.contextId.trim().length>0?t.contextId.trim():typeof i.contextId=="string"&&i.contextId.trim().length>0?i.contextId.trim():void 0,l=typeof t.agentId=="string"&&t.agentId.trim().length>0?t.agentId.trim():void 0,o=t.metadata,r=o&&typeof o=="object"&&!Array.isArray(o)?o:void 0,a=t.configuration,f=a&&typeof a=="object"&&!Array.isArray(a)?a.pushNotificationConfig??a.taskPushNotificationConfig:void 0,d=N(t.pushNotificationConfig??f);return{input:u.join(`
5
+
6
+ `),...l?{agentId:l}:{},...g?{sessionId:g}:{},...r?{invocation:r}:{},...d?{pushNotificationConfig:d}:{}}}function R(e,t){return{...e??{},protocol:{...e?.protocol&&typeof e.protocol=="object"&&!Array.isArray(e.protocol)?e.protocol:{},a2a:{version:t.version,...t.extensions.length>0?{extensions:t.extensions}:{}}}}}function q(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("A2A task lookup requires params object.");const t=e,s=typeof t.id=="string"&&t.id.trim().length>0?t.id.trim():typeof t.taskId=="string"&&t.taskId.trim().length>0?t.taskId.trim():"";if(!s)throw new Error("A2A task lookup requires `id`.");return{taskId:s}}function Q(e){if(!e||typeof e!="object"||Array.isArray(e))return{limit:20};const t=e,s=typeof t.pageSize=="number"&&Number.isFinite(t.pageSize)?t.pageSize:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:20,i=typeof s=="number"&&Number.isFinite(s)?Math.max(1,Math.min(100,Math.trunc(s))):20;return{...typeof t.agentId=="string"&&t.agentId.trim().length>0?{agentId:t.agentId.trim()}:{},...typeof t.contextId=="string"&&t.contextId.trim().length>0?{contextId:t.contextId.trim()}:{},...typeof t.status=="string"&&t.status.trim().length>0?{state:t.status.trim()}:typeof t.state=="string"&&t.state.trim().length>0?{state:t.state.trim()}:{},...typeof t.pageToken=="string"&&t.pageToken.trim().length>0?{cursor:t.pageToken.trim()}:typeof t.cursor=="string"&&t.cursor.trim().length>0?{cursor:t.cursor.trim()}:{},limit:i}}function j(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("A2A push notification lookup requires params object.");const t=e,s=typeof t.taskId=="string"&&t.taskId.trim().length>0?t.taskId.trim():"",i=typeof t.id=="string"&&t.id.trim().length>0?t.id.trim():"";if(!s)throw new Error("A2A push notification lookup requires `taskId`.");if(!i)throw new Error("A2A push notification lookup requires `id`.");return{taskId:s,configId:i}}function W(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("A2A push notification list requires params object.");const t=e,s=typeof t.taskId=="string"&&t.taskId.trim().length>0?t.taskId.trim():"";if(!s)throw new Error("A2A push notification list requires `taskId`.");const i=typeof t.pageSize=="number"&&Number.isFinite(t.pageSize)?Math.max(1,Math.min(100,Math.trunc(t.pageSize))):20;return{taskId:s,pageSize:i,...typeof t.pageToken=="string"&&t.pageToken.trim().length>0?{pageToken:t.pageToken.trim()}:{}}}function X(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("A2A push notification create requires params object.");const t=e,s=typeof t.taskId=="string"&&t.taskId.trim().length>0?t.taskId.trim():"";if(!s)throw new Error("A2A push notification create requires `taskId`.");const i=N(t.pushNotificationConfig??t.config??t);if(!i)throw new Error("A2A push notification create requires a config object.");return{taskId:s,config:i}}async function Y(e,t){const s={"content-type":"application/json"};e.token&&(s["x-a2a-notification-token"]=e.token);const i=e.authentication?.schemes[0]?.toLowerCase();i==="bearer"&&e.authentication?.credentials?s.authorization=`Bearer ${e.authentication.credentials}`:i==="basic"&&e.authentication?.credentials&&(s.authorization=`Basic ${e.authentication.credentials}`),await fetch(e.url,{method:"POST",headers:s,body:JSON.stringify({task:t})})}async function Z(e,t,s,i){P(e);for await(const n of i)n.task&&await A(e,"task-update",h(t,S(s,n.task,n.mode)));e.end()}async function*tt(e,t,s){let i,n="",c=!1;for await(const u of e.streamEvents(t)){if(u.type==="event"){if(i=i??u.event.requestId,u.event.eventType==="output.delta"&&typeof u.event.payload.content=="string"&&(n+=u.event.payload.content),u.event.eventType==="request.created"||u.event.eventType==="request.state.changed"||u.event.eventType==="output.delta"||u.event.eventType==="approval.requested"){const g=C(await w(e,u.event.requestId),n||void 0);g&&(yield{task:g,mode:c?"status-update":"task"},c=!0)}continue}if(u.type==="result"){yield{task:_(await w(e,u.result.requestId),u.result,n||u.result.output),mode:c?"status-update":"task"};return}if(u.type==="upstream-event"&&i){const g=C(await w(e,i),n||void 0);g&&(yield{task:g,mode:c?"status-update":"task"},c=!0)}}}async function et(e,t,s,i,n){P(t);let c=await b(e,await w(e,n));if(!c){await A(t,"error",k(s,-32001,"Task not found.")),t.end();return}if(await A(t,"task-update",h(s,S(i,c,"task"))),I(c.status.state)){t.end();return}await new Promise(u=>{let g=!1,l,o=JSON.stringify({state:c?.status.state,message:c?.status.message});const r=()=>{l&&clearTimeout(l),l=setTimeout(()=>{t.end(),a()},1e3)},a=()=>{g||(g=!0,d(),clearInterval(m),l&&clearTimeout(l),u())},f=async()=>{if(c=await b(e,await w(e,n)),!c){await A(t,"error",k(s,-32001,"Task not found.")),t.end(),a();return}const y=JSON.stringify({state:c.status.state,message:c.status.message});y!==o&&(o=y,await A(t,"task-update",h(s,S(i,c,O(i)?"status-update":"task"))),r()),I(c.status.state)&&(t.end(),a())},d=e.subscribe(y=>{y.requestId===n&&(y.eventType!=="request.state.changed"&&y.eventType!=="output.delta"&&y.eventType!=="approval.requested"&&y.eventType!=="approval.resolved"||f())}),m=setInterval(()=>{f()},250);r(),t.on("close",a)})}function rt(e,t){const s=new Map,i=(r,a)=>{const f={id:a.id??`push-${t()}`,taskId:r,url:a.url,...a.token?{token:a.token}:{},...a.authentication?{authentication:a.authentication}:{}};let d=s.get(r);return d||(d=new Map,s.set(r,d)),d.set(f.id,f),f},n=r=>[...s.get(r)?.values()??[]].sort((a,f)=>a.id.localeCompare(f.id)),c=(r,a)=>s.get(r)?.get(a),u=(r,a)=>{const f=s.get(r);if(!f)return!1;const d=f.delete(a);return f.size===0&&s.delete(r),d},g=async r=>{const a=await b(e,await w(e,r));if(!a)return;const f=B(a),d=n(r);await Promise.all(d.map(async m=>{if(m.lastFingerprint!==f)try{await Y(m,a),m.lastFingerprint=f}catch{}}))},l=new Set(["request.state.changed","approval.requested","approval.resolved"]),o=e.subscribe(r=>{!l.has(r.eventType)||!s.has(r.requestId)||g(r.requestId)});return{register:i,list:n,get:c,delete:u,dispatch:g,unsubscribe:o}}async function ot(e){const{runtime:t,request:s,response:i,payload:n,serviceParameters:c,serverOptions:u,buildCardOptions:g,pushNotifications:l}=e;if(n.method==="message/send"||n.method==="tasks/send"||n.method==="SendMessage"){const o=E(n.params),r=await t.run({agentId:o.agentId??u.defaultAgentId,input:o.input,...o.sessionId?{sessionId:o.sessionId}:{},invocation:R(o.invocation,c)}),a=await t.getSessionRecord(r.sessionId),f=await t.getRequest(r.requestId),d=await t.listApprovals({sessionId:r.sessionId,requestId:r.requestId}),m=F(G(a),$(f),d,r.output);m&&o.pushNotificationConfig&&(l.register(m.id,o.pushNotificationConfig),await l.dispatch(m.id)),p(i,200,h(n.id??null,H(n.method,m)));return}if(n.method==="GetAgentCard"){x(i,{registryUrls:u.registryUrls,agentCardSignature:u.agentCardSignature}),p(i,200,h(n.id??null,U(t,g())));return}if(n.method==="message/stream"||n.method==="SendStreamingMessage"){if(!v(s)){p(i,406,k(n.id??null,-32004,"A2A streaming requires `Accept: text/event-stream`."));return}const o=E(n.params);let r;const a=tt(t,{agentId:o.agentId??u.defaultAgentId,input:o.input,...o.sessionId?{sessionId:o.sessionId}:{},invocation:R(o.invocation,c)},n.method),f=(async function*(){for await(const d of a)d.task&&o.pushNotificationConfig&&!r&&(r=d.task.id,l.register(d.task.id,o.pushNotificationConfig),await l.dispatch(d.task.id)),yield d})();await Z(i,n.id??null,n.method,f);return}if(n.method==="tasks/get"||n.method==="GetTask"){const{taskId:o}=q(n.params),r=await w(t,o);if(!r){p(i,200,k(n.id??null,-32001,"Task not found."));return}p(i,200,h(n.id??null,r));return}if(n.method==="tasks/list"||n.method==="ListTasks"){const o=await J(t,Q(n.params));p(i,200,h(n.id??null,o));return}if(n.method==="tasks/cancel"||n.method==="CancelTask"){const{taskId:o}=q(n.params),r=await t.cancelRequest({requestId:o,reason:"Cancelled via A2A bridge."}),a=await w(t,r.requestId);p(i,200,h(n.id??null,a));return}if(n.method==="tasks/subscribe"||n.method==="SubscribeToTask"){const{taskId:o}=q(n.params),r=await w(t,o);if(!r){p(i,200,k(n.id??null,-32001,"Task not found."));return}if(n.method==="SubscribeToTask"){if(I(r.status.state)){p(i,200,k(n.id??null,-32004,"SubscribeToTask is not supported for tasks in terminal state."));return}if(!v(s)){p(i,406,k(n.id??null,-32004,"A2A streaming subscriptions require `Accept: text/event-stream`."));return}await et(t,i,n.id??null,n.method,o);return}p(i,200,h(n.id??null,{task:r,streamable:!1,pushNotifications:!0,nextPollAfterMs:I(r.status.state)?0:1e3}));return}if(n.method==="CreateTaskPushNotificationConfig"){const{taskId:o,config:r}=X(n.params);if(!await w(t,o)){p(i,200,k(n.id??null,-32001,"Task not found."));return}const a=l.register(o,r);await l.dispatch(o),p(i,200,h(n.id??null,T(a)));return}if(n.method==="GetTaskPushNotificationConfig"){const{taskId:o,configId:r}=j(n.params),a=l.get(o,r);if(!a){p(i,200,k(n.id??null,-32001,"Push notification config not found."));return}p(i,200,h(n.id??null,T(a)));return}if(n.method==="ListTaskPushNotificationConfigs"){const{taskId:o,pageSize:r,pageToken:a}=W(n.params),f=l.list(o),d=a&&Number.parseInt(Buffer.from(a,"base64url").toString("utf8"),10)||0,m=f.slice(d,d+r).map(T),y=d+m.length,M=y<f.length?Buffer.from(String(y),"utf8").toString("base64url"):"",L={configs:m,nextPageToken:M};p(i,200,h(n.id??null,L));return}if(n.method==="DeleteTaskPushNotificationConfig"){const{taskId:o,configId:r}=j(n.params);if(!l.delete(o,r)){p(i,200,k(n.id??null,-32001,"Push notification config not found."));return}p(i,200,h(n.id??null,{deleted:!0,id:r,taskId:o}));return}if(n.method==="GetExtendedAgentCard"){x(i,{registryUrls:u.registryUrls,agentCardSignature:u.agentCardSignature}),p(i,200,h(n.id??null,z(t,g())));return}p(i,200,k(n.id??null,-32601,`Unknown A2A method: ${n.method}`))}export{rt as createPushNotificationRegistry,ot as handleA2aJsonRpcRequest,st as readRequestBody,k as toError};