@a2a-js/sdk 0.2.1

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 (49) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +422 -0
  3. package/build/src/a2a_response.d.ts +5 -0
  4. package/build/src/a2a_response.js +2 -0
  5. package/build/src/client/client.d.ts +118 -0
  6. package/build/src/client/client.js +409 -0
  7. package/build/src/index.d.ts +21 -0
  8. package/build/src/index.js +18 -0
  9. package/build/src/samples/agents/movie-agent/genkit.d.ts +2 -0
  10. package/build/src/samples/agents/movie-agent/genkit.js +11 -0
  11. package/build/src/samples/agents/movie-agent/index.d.ts +1 -0
  12. package/build/src/samples/agents/movie-agent/index.js +252 -0
  13. package/build/src/samples/agents/movie-agent/tmdb.d.ts +7 -0
  14. package/build/src/samples/agents/movie-agent/tmdb.js +32 -0
  15. package/build/src/samples/agents/movie-agent/tools.d.ts +15 -0
  16. package/build/src/samples/agents/movie-agent/tools.js +74 -0
  17. package/build/src/samples/cli.d.ts +2 -0
  18. package/build/src/samples/cli.js +289 -0
  19. package/build/src/server/a2a_express_app.d.ts +14 -0
  20. package/build/src/server/a2a_express_app.js +98 -0
  21. package/build/src/server/agent_execution/agent_executor.d.ts +18 -0
  22. package/build/src/server/agent_execution/agent_executor.js +2 -0
  23. package/build/src/server/agent_execution/request_context.d.ts +9 -0
  24. package/build/src/server/agent_execution/request_context.js +15 -0
  25. package/build/src/server/error.d.ts +23 -0
  26. package/build/src/server/error.js +57 -0
  27. package/build/src/server/events/execution_event_bus.d.ts +16 -0
  28. package/build/src/server/events/execution_event_bus.js +13 -0
  29. package/build/src/server/events/execution_event_bus_manager.d.ts +27 -0
  30. package/build/src/server/events/execution_event_bus_manager.js +36 -0
  31. package/build/src/server/events/execution_event_queue.d.ts +24 -0
  32. package/build/src/server/events/execution_event_queue.js +63 -0
  33. package/build/src/server/request_handler/a2a_request_handler.d.ts +11 -0
  34. package/build/src/server/request_handler/a2a_request_handler.js +2 -0
  35. package/build/src/server/request_handler/default_request_handler.d.ts +22 -0
  36. package/build/src/server/request_handler/default_request_handler.js +296 -0
  37. package/build/src/server/result_manager.d.ts +29 -0
  38. package/build/src/server/result_manager.js +149 -0
  39. package/build/src/server/store.d.ts +25 -0
  40. package/build/src/server/store.js +17 -0
  41. package/build/src/server/transports/jsonrpc_transport_handler.d.ts +15 -0
  42. package/build/src/server/transports/jsonrpc_transport_handler.js +114 -0
  43. package/build/src/server/utils.d.ts +22 -0
  44. package/build/src/server/utils.js +34 -0
  45. package/build/src/types-old.d.ts +832 -0
  46. package/build/src/types-old.js +20 -0
  47. package/build/src/types.d.ts +2046 -0
  48. package/build/src/types.js +8 -0
  49. package/package.json +52 -0
@@ -0,0 +1,118 @@
1
+ import { AgentCard, JSONRPCResponse, JSONRPCErrorResponse, Message, Task, TaskStatusUpdateEvent, TaskArtifactUpdateEvent, MessageSendParams, SendMessageResponse, TaskQueryParams, GetTaskResponse, TaskIdParams, CancelTaskResponse, TaskPushNotificationConfig, SetTaskPushNotificationConfigResponse, GetTaskPushNotificationConfigResponse } from '../types.js';
2
+ type A2AStreamEventData = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
3
+ /**
4
+ * A2AClient is a TypeScript HTTP client for interacting with A2A-compliant agents.
5
+ */
6
+ export declare class A2AClient {
7
+ private agentBaseUrl;
8
+ private agentCardPromise;
9
+ private requestIdCounter;
10
+ private serviceEndpointUrl?;
11
+ /**
12
+ * Constructs an A2AClient instance.
13
+ * It initiates fetching the agent card from the provided agent baseUrl.
14
+ * The Agent Card is expected at `${agentBaseUrl}/.well-known/agent.json`.
15
+ * The `url` field from the Agent Card will be used as the RPC service endpoint.
16
+ * @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com).
17
+ */
18
+ constructor(agentBaseUrl: string);
19
+ /**
20
+ * Fetches the Agent Card from the agent's well-known URI and caches its service endpoint URL.
21
+ * This method is called by the constructor.
22
+ * @returns A Promise that resolves to the AgentCard.
23
+ */
24
+ private _fetchAndCacheAgentCard;
25
+ /**
26
+ * Retrieves the Agent Card.
27
+ * If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
28
+ * Otherwise, it returns the card fetched and cached during client construction.
29
+ * @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
30
+ * If provided, this will fetch a new card, not use the cached one from the constructor's URL.
31
+ * @returns A Promise that resolves to the AgentCard.
32
+ */
33
+ getAgentCard(agentBaseUrl?: string): Promise<AgentCard>;
34
+ /**
35
+ * Gets the RPC service endpoint URL. Ensures the agent card has been fetched first.
36
+ * @returns A Promise that resolves to the service endpoint URL string.
37
+ */
38
+ private _getServiceEndpoint;
39
+ /**
40
+ * Helper method to make a generic JSON-RPC POST request.
41
+ * @param method The RPC method name.
42
+ * @param params The parameters for the RPC method.
43
+ * @returns A Promise that resolves to the RPC response.
44
+ */
45
+ private _postRpcRequest;
46
+ /**
47
+ * Sends a message to the agent.
48
+ * The behavior (blocking/non-blocking) and push notification configuration
49
+ * are specified within the `params.configuration` object.
50
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
51
+ * @param params The parameters for sending the message, including the message content and configuration.
52
+ * @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
53
+ */
54
+ sendMessage(params: MessageSendParams): Promise<SendMessageResponse>;
55
+ /**
56
+ * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
57
+ * Push notification configuration can be specified in `params.configuration`.
58
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
59
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
60
+ * @param params The parameters for sending the message.
61
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
62
+ * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
63
+ */
64
+ sendMessageStream(params: MessageSendParams): AsyncGenerator<A2AStreamEventData, void, undefined>;
65
+ /**
66
+ * Sets or updates the push notification configuration for a given task.
67
+ * Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
68
+ * @param params Parameters containing the taskId and the TaskPushNotificationConfig.
69
+ * @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
70
+ */
71
+ setTaskPushNotificationConfig(params: TaskPushNotificationConfig): Promise<SetTaskPushNotificationConfigResponse>;
72
+ /**
73
+ * Gets the push notification configuration for a given task.
74
+ * @param params Parameters containing the taskId.
75
+ * @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
76
+ */
77
+ getTaskPushNotificationConfig(params: TaskIdParams): Promise<GetTaskPushNotificationConfigResponse>;
78
+ /**
79
+ * Retrieves a task by its ID.
80
+ * @param params Parameters containing the taskId and optional historyLength.
81
+ * @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
82
+ */
83
+ getTask(params: TaskQueryParams): Promise<GetTaskResponse>;
84
+ /**
85
+ * Cancels a task by its ID.
86
+ * @param params Parameters containing the taskId.
87
+ * @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
88
+ */
89
+ cancelTask(params: TaskIdParams): Promise<CancelTaskResponse>;
90
+ /**
91
+ * Resubscribes to a task's event stream using Server-Sent Events (SSE).
92
+ * This is used if a previous SSE connection for an active task was broken.
93
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
94
+ * @param params Parameters containing the taskId.
95
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
96
+ */
97
+ resubscribeTask(params: TaskIdParams): AsyncGenerator<A2AStreamEventData, void, undefined>;
98
+ /**
99
+ * Parses an HTTP response body as an A2A Server-Sent Event stream.
100
+ * Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,
101
+ * specifically a SendStreamingMessageResponse (or similar structure for resubscribe).
102
+ * @param response The HTTP Response object whose body is the SSE stream.
103
+ * @param originalRequestId The ID of the client's JSON-RPC request that initiated this stream.
104
+ * Used to validate the `id` in the streamed JSON-RPC responses.
105
+ * @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.
106
+ */
107
+ private _parseA2ASseStream;
108
+ /**
109
+ * Processes a single SSE event's data string, expecting it to be a JSON-RPC response.
110
+ * @param jsonData The string content from one or more 'data:' lines of an SSE event.
111
+ * @param originalRequestId The ID of the client's request that initiated the stream.
112
+ * @returns The `result` field of the parsed JSON-RPC success response.
113
+ * @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.
114
+ */
115
+ private _processSseEventData;
116
+ isErrorResponse(response: JSONRPCResponse): response is JSONRPCErrorResponse;
117
+ }
118
+ export {};
@@ -0,0 +1,409 @@
1
+ /**
2
+ * A2AClient is a TypeScript HTTP client for interacting with A2A-compliant agents.
3
+ */
4
+ export class A2AClient {
5
+ agentBaseUrl;
6
+ agentCardPromise;
7
+ requestIdCounter = 1;
8
+ serviceEndpointUrl; // To be populated from AgentCard after fetching
9
+ /**
10
+ * Constructs an A2AClient instance.
11
+ * It initiates fetching the agent card from the provided agent baseUrl.
12
+ * The Agent Card is expected at `${agentBaseUrl}/.well-known/agent.json`.
13
+ * The `url` field from the Agent Card will be used as the RPC service endpoint.
14
+ * @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com).
15
+ */
16
+ constructor(agentBaseUrl) {
17
+ this.agentBaseUrl = agentBaseUrl.replace(/\/$/, ""); // Remove trailing slash if any
18
+ this.agentCardPromise = this._fetchAndCacheAgentCard();
19
+ }
20
+ /**
21
+ * Fetches the Agent Card from the agent's well-known URI and caches its service endpoint URL.
22
+ * This method is called by the constructor.
23
+ * @returns A Promise that resolves to the AgentCard.
24
+ */
25
+ async _fetchAndCacheAgentCard() {
26
+ const agentCardUrl = `${this.agentBaseUrl}/.well-known/agent.json`;
27
+ try {
28
+ const response = await fetch(agentCardUrl, {
29
+ headers: { 'Accept': 'application/json' },
30
+ });
31
+ if (!response.ok) {
32
+ throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`);
33
+ }
34
+ const agentCard = await response.json();
35
+ if (!agentCard.url) {
36
+ throw new Error("Fetched Agent Card does not contain a valid 'url' for the service endpoint.");
37
+ }
38
+ this.serviceEndpointUrl = agentCard.url; // Cache the service endpoint URL from the agent card
39
+ console.log("ENDOPINT", this.serviceEndpointUrl);
40
+ return agentCard;
41
+ }
42
+ catch (error) {
43
+ console.error("Error fetching or parsing Agent Card:");
44
+ // Allow the promise to reject so users of agentCardPromise can handle it.
45
+ throw error;
46
+ }
47
+ }
48
+ /**
49
+ * Retrieves the Agent Card.
50
+ * If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
51
+ * Otherwise, it returns the card fetched and cached during client construction.
52
+ * @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
53
+ * If provided, this will fetch a new card, not use the cached one from the constructor's URL.
54
+ * @returns A Promise that resolves to the AgentCard.
55
+ */
56
+ async getAgentCard(agentBaseUrl) {
57
+ if (agentBaseUrl) {
58
+ const specificAgentBaseUrl = agentBaseUrl.replace(/\/$/, "");
59
+ const agentCardUrl = `${specificAgentBaseUrl}/.well-known/agent.json`;
60
+ const response = await fetch(agentCardUrl, {
61
+ headers: { 'Accept': 'application/json' },
62
+ });
63
+ if (!response.ok) {
64
+ throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`);
65
+ }
66
+ return await response.json();
67
+ }
68
+ // If no specific URL is given, return the promise for the initially configured agent's card.
69
+ return this.agentCardPromise;
70
+ }
71
+ /**
72
+ * Gets the RPC service endpoint URL. Ensures the agent card has been fetched first.
73
+ * @returns A Promise that resolves to the service endpoint URL string.
74
+ */
75
+ async _getServiceEndpoint() {
76
+ if (this.serviceEndpointUrl) {
77
+ return this.serviceEndpointUrl;
78
+ }
79
+ // If serviceEndpointUrl is not set, it means the agent card fetch is pending or failed.
80
+ // Awaiting agentCardPromise will either resolve it or throw if fetching failed.
81
+ await this.agentCardPromise;
82
+ if (!this.serviceEndpointUrl) {
83
+ // This case should ideally be covered by the error handling in _fetchAndCacheAgentCard
84
+ throw new Error("Agent Card URL for RPC endpoint is not available. Fetching might have failed.");
85
+ }
86
+ return this.serviceEndpointUrl;
87
+ }
88
+ /**
89
+ * Helper method to make a generic JSON-RPC POST request.
90
+ * @param method The RPC method name.
91
+ * @param params The parameters for the RPC method.
92
+ * @returns A Promise that resolves to the RPC response.
93
+ */
94
+ async _postRpcRequest(method, params) {
95
+ const endpoint = await this._getServiceEndpoint();
96
+ const requestId = this.requestIdCounter++;
97
+ const rpcRequest = {
98
+ jsonrpc: "2.0",
99
+ method,
100
+ params: params, // Cast because TParams structure varies per method
101
+ id: requestId,
102
+ };
103
+ const httpResponse = await fetch(endpoint, {
104
+ method: "POST",
105
+ headers: {
106
+ "Content-Type": "application/json",
107
+ "Accept": "application/json", // Expect JSON response for non-streaming requests
108
+ },
109
+ body: JSON.stringify(rpcRequest),
110
+ });
111
+ if (!httpResponse.ok) {
112
+ let errorBodyText = '(empty or non-JSON response)';
113
+ try {
114
+ errorBodyText = await httpResponse.text();
115
+ const errorJson = JSON.parse(errorBodyText);
116
+ // If the body is a valid JSON-RPC error response, let it be handled by the standard parsing below.
117
+ // However, if it's not even a JSON-RPC structure but still an error, throw based on HTTP status.
118
+ if (!errorJson.jsonrpc && errorJson.error) { // Check if it's a JSON-RPC error structure
119
+ throw new Error(`RPC error for ${method}: ${errorJson.error.message} (Code: ${errorJson.error.code}, HTTP Status: ${httpResponse.status}) Data: ${JSON.stringify(errorJson.error.data)}`);
120
+ }
121
+ else if (!errorJson.jsonrpc) {
122
+ throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
123
+ }
124
+ }
125
+ catch (e) {
126
+ // If parsing the error body fails or it's not a JSON-RPC error, throw a generic HTTP error.
127
+ // If it was already an error thrown from within the try block, rethrow it.
128
+ if (e.message.startsWith('RPC error for') || e.message.startsWith('HTTP error for'))
129
+ throw e;
130
+ throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
131
+ }
132
+ }
133
+ const rpcResponse = await httpResponse.json();
134
+ if (rpcResponse.id !== requestId) {
135
+ // This is a significant issue for request-response matching.
136
+ console.error(`CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}. This may lead to incorrect response handling.`);
137
+ // Depending on strictness, one might throw an error here.
138
+ // throw new Error(`RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}`);
139
+ }
140
+ return rpcResponse;
141
+ }
142
+ /**
143
+ * Sends a message to the agent.
144
+ * The behavior (blocking/non-blocking) and push notification configuration
145
+ * are specified within the `params.configuration` object.
146
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
147
+ * @param params The parameters for sending the message, including the message content and configuration.
148
+ * @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
149
+ */
150
+ async sendMessage(params) {
151
+ return this._postRpcRequest("message/send", params);
152
+ }
153
+ /**
154
+ * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
155
+ * Push notification configuration can be specified in `params.configuration`.
156
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
157
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
158
+ * @param params The parameters for sending the message.
159
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
160
+ * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
161
+ */
162
+ async *sendMessageStream(params) {
163
+ const agentCard = await this.agentCardPromise; // Ensure agent card is fetched
164
+ if (!agentCard.capabilities?.streaming) {
165
+ throw new Error("Agent does not support streaming (AgentCard.capabilities.streaming is not true).");
166
+ }
167
+ const endpoint = await this._getServiceEndpoint();
168
+ const clientRequestId = this.requestIdCounter++; // Use a unique ID for this stream request
169
+ const rpcRequest = {
170
+ jsonrpc: "2.0",
171
+ method: "message/stream",
172
+ params: params,
173
+ id: clientRequestId,
174
+ };
175
+ const response = await fetch(endpoint, {
176
+ method: "POST",
177
+ headers: {
178
+ "Content-Type": "application/json",
179
+ "Accept": "text/event-stream", // Crucial for SSE
180
+ },
181
+ body: JSON.stringify(rpcRequest),
182
+ });
183
+ if (!response.ok) {
184
+ // Attempt to read error body for more details
185
+ let errorBody = "";
186
+ try {
187
+ errorBody = await response.text();
188
+ const errorJson = JSON.parse(errorBody);
189
+ if (errorJson.error) {
190
+ throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
191
+ }
192
+ }
193
+ catch (e) {
194
+ if (e.message.startsWith('HTTP error establishing stream'))
195
+ throw e;
196
+ // Fallback if body is not JSON or parsing fails
197
+ throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`);
198
+ }
199
+ throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}`);
200
+ }
201
+ if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
202
+ // Server should explicitly set this content type for SSE.
203
+ throw new Error("Invalid response Content-Type for SSE stream. Expected 'text/event-stream'.");
204
+ }
205
+ // Yield events from the parsed SSE stream.
206
+ // Each event's 'data' field is a JSON-RPC response.
207
+ yield* this._parseA2ASseStream(response, clientRequestId);
208
+ }
209
+ /**
210
+ * Sets or updates the push notification configuration for a given task.
211
+ * Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
212
+ * @param params Parameters containing the taskId and the TaskPushNotificationConfig.
213
+ * @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
214
+ */
215
+ async setTaskPushNotificationConfig(params) {
216
+ const agentCard = await this.agentCardPromise;
217
+ if (!agentCard.capabilities?.pushNotifications) {
218
+ throw new Error("Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true).");
219
+ }
220
+ // The 'params' directly matches the structure expected by the RPC method.
221
+ return this._postRpcRequest("tasks/pushNotificationConfig/set", params);
222
+ }
223
+ /**
224
+ * Gets the push notification configuration for a given task.
225
+ * @param params Parameters containing the taskId.
226
+ * @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
227
+ */
228
+ async getTaskPushNotificationConfig(params) {
229
+ // The 'params' (TaskIdParams) directly matches the structure expected by the RPC method.
230
+ return this._postRpcRequest("tasks/pushNotificationConfig/get", params);
231
+ }
232
+ /**
233
+ * Retrieves a task by its ID.
234
+ * @param params Parameters containing the taskId and optional historyLength.
235
+ * @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
236
+ */
237
+ async getTask(params) {
238
+ return this._postRpcRequest("tasks/get", params);
239
+ }
240
+ /**
241
+ * Cancels a task by its ID.
242
+ * @param params Parameters containing the taskId.
243
+ * @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
244
+ */
245
+ async cancelTask(params) {
246
+ return this._postRpcRequest("tasks/cancel", params);
247
+ }
248
+ /**
249
+ * Resubscribes to a task's event stream using Server-Sent Events (SSE).
250
+ * This is used if a previous SSE connection for an active task was broken.
251
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
252
+ * @param params Parameters containing the taskId.
253
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
254
+ */
255
+ async *resubscribeTask(params) {
256
+ const agentCard = await this.agentCardPromise;
257
+ if (!agentCard.capabilities?.streaming) {
258
+ throw new Error("Agent does not support streaming (required for tasks/resubscribe).");
259
+ }
260
+ const endpoint = await this._getServiceEndpoint();
261
+ const clientRequestId = this.requestIdCounter++; // Unique ID for this resubscribe request
262
+ const rpcRequest = {
263
+ jsonrpc: "2.0",
264
+ method: "tasks/resubscribe",
265
+ params: params,
266
+ id: clientRequestId,
267
+ };
268
+ const response = await fetch(endpoint, {
269
+ method: "POST",
270
+ headers: {
271
+ "Content-Type": "application/json",
272
+ "Accept": "text/event-stream",
273
+ },
274
+ body: JSON.stringify(rpcRequest),
275
+ });
276
+ if (!response.ok) {
277
+ let errorBody = "";
278
+ try {
279
+ errorBody = await response.text();
280
+ const errorJson = JSON.parse(errorBody);
281
+ if (errorJson.error) {
282
+ throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
283
+ }
284
+ }
285
+ catch (e) {
286
+ if (e.message.startsWith('HTTP error establishing stream'))
287
+ throw e;
288
+ throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. Response: ${errorBody || '(empty)'}`);
289
+ }
290
+ throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}`);
291
+ }
292
+ if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
293
+ throw new Error("Invalid response Content-Type for SSE stream on resubscribe. Expected 'text/event-stream'.");
294
+ }
295
+ // The events structure for resubscribe is assumed to be the same as message/stream.
296
+ // Each event's 'data' field is a JSON-RPC response.
297
+ yield* this._parseA2ASseStream(response, clientRequestId);
298
+ }
299
+ /**
300
+ * Parses an HTTP response body as an A2A Server-Sent Event stream.
301
+ * Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,
302
+ * specifically a SendStreamingMessageResponse (or similar structure for resubscribe).
303
+ * @param response The HTTP Response object whose body is the SSE stream.
304
+ * @param originalRequestId The ID of the client's JSON-RPC request that initiated this stream.
305
+ * Used to validate the `id` in the streamed JSON-RPC responses.
306
+ * @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.
307
+ */
308
+ async *_parseA2ASseStream(response, originalRequestId) {
309
+ if (!response.body) {
310
+ throw new Error("SSE response body is undefined. Cannot read stream.");
311
+ }
312
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
313
+ let buffer = ""; // Holds incomplete lines from the stream
314
+ let eventDataBuffer = ""; // Holds accumulated 'data:' lines for the current event
315
+ try {
316
+ while (true) {
317
+ const { done, value } = await reader.read();
318
+ if (done) {
319
+ // Process any final buffered event data if the stream ends abruptly after a 'data:' line
320
+ if (eventDataBuffer.trim()) {
321
+ const result = this._processSseEventData(eventDataBuffer, originalRequestId);
322
+ yield result;
323
+ }
324
+ break; // Stream finished
325
+ }
326
+ buffer += value; // Append new chunk to buffer
327
+ let lineEndIndex;
328
+ // Process all complete lines in the buffer
329
+ while ((lineEndIndex = buffer.indexOf('\n')) >= 0) {
330
+ const line = buffer.substring(0, lineEndIndex).trim(); // Get and trim the line
331
+ buffer = buffer.substring(lineEndIndex + 1); // Remove processed line from buffer
332
+ if (line === "") { // Empty line: signifies the end of an event
333
+ if (eventDataBuffer) { // If we have accumulated data for an event
334
+ const result = this._processSseEventData(eventDataBuffer, originalRequestId);
335
+ yield result;
336
+ eventDataBuffer = ""; // Reset buffer for the next event
337
+ }
338
+ }
339
+ else if (line.startsWith("data:")) {
340
+ eventDataBuffer += line.substring(5).trimStart() + "\n"; // Append data (multi-line data is possible)
341
+ }
342
+ else if (line.startsWith(":")) {
343
+ // This is a comment line in SSE, ignore it.
344
+ }
345
+ else if (line.includes(":")) {
346
+ // Other SSE fields like 'event:', 'id:', 'retry:'.
347
+ // The A2A spec primarily focuses on the 'data' field for JSON-RPC payloads.
348
+ // For now, we don't specifically handle these other SSE fields unless required by spec.
349
+ }
350
+ }
351
+ }
352
+ }
353
+ catch (error) {
354
+ // Log and re-throw errors encountered during stream processing
355
+ console.error("Error reading or parsing SSE stream:", error.message);
356
+ throw error;
357
+ }
358
+ finally {
359
+ reader.releaseLock(); // Ensure the reader lock is released
360
+ }
361
+ }
362
+ /**
363
+ * Processes a single SSE event's data string, expecting it to be a JSON-RPC response.
364
+ * @param jsonData The string content from one or more 'data:' lines of an SSE event.
365
+ * @param originalRequestId The ID of the client's request that initiated the stream.
366
+ * @returns The `result` field of the parsed JSON-RPC success response.
367
+ * @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.
368
+ */
369
+ _processSseEventData(jsonData, originalRequestId) {
370
+ if (!jsonData.trim()) {
371
+ throw new Error("Attempted to process empty SSE event data.");
372
+ }
373
+ try {
374
+ // SSE data can be multi-line, ensure it's treated as a single JSON string.
375
+ const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\n$/, '')); // Remove trailing newline if any
376
+ // Type assertion to SendStreamingMessageResponse, as this is the expected structure for A2A streams.
377
+ const a2aStreamResponse = sseJsonRpcResponse;
378
+ if (a2aStreamResponse.id !== originalRequestId) {
379
+ // According to JSON-RPC spec, notifications (which SSE events can be seen as) might not have an ID,
380
+ // or if they do, it should match. A2A spec implies streamed events are tied to the initial request.
381
+ console.warn(`SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`);
382
+ // Depending on strictness, this could be an error. For now, it's a warning.
383
+ }
384
+ if (this.isErrorResponse(a2aStreamResponse)) {
385
+ const err = a2aStreamResponse.error;
386
+ throw new Error(`SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data)}`);
387
+ }
388
+ // Check if 'result' exists, as it's mandatory for successful JSON-RPC responses
389
+ if (!('result' in a2aStreamResponse) || typeof a2aStreamResponse.result === 'undefined') {
390
+ throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
391
+ }
392
+ const successResponse = a2aStreamResponse;
393
+ return successResponse.result;
394
+ }
395
+ catch (e) {
396
+ // Catch errors from JSON.parse or if it's an error response that was thrown by this function
397
+ if (e.message.startsWith("SSE event contained an error") || e.message.startsWith("SSE event JSON-RPC response is missing 'result' field")) {
398
+ throw e; // Re-throw errors already processed/identified by this function
399
+ }
400
+ // For other parsing errors or unexpected structures:
401
+ console.error("Failed to parse SSE event data string or unexpected JSON-RPC structure:", jsonData, e);
402
+ throw new Error(`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${e.message}`);
403
+ }
404
+ }
405
+ isErrorResponse(response) {
406
+ return "error" in response;
407
+ }
408
+ }
409
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Main entry point for the A2A Server V2 library.
3
+ * Exports the server class, store implementations, and core types.
4
+ */
5
+ export type { AgentExecutor } from "./server/agent_execution/agent_executor.js";
6
+ export { RequestContext } from "./server/agent_execution/request_context.js";
7
+ export type { ExecutionEventBus } from "./server/events/execution_event_bus.js";
8
+ export { DefaultExecutionEventBus } from "./server/events/execution_event_bus.js";
9
+ export type { ExecutionEventBusManager } from "./server/events/execution_event_bus_manager.js";
10
+ export { DefaultExecutionEventBusManager } from "./server/events/execution_event_bus_manager.js";
11
+ export type { A2ARequestHandler } from "./server/request_handler/a2a_request_handler.js";
12
+ export { DefaultRequestHandler } from "./server/request_handler/default_request_handler.js";
13
+ export { ResultManager } from "./server/result_manager.js";
14
+ export type { TaskStore } from "./server/store.js";
15
+ export { InMemoryTaskStore } from "./server/store.js";
16
+ export { JsonRpcTransportHandler } from "./server/transports/jsonrpc_transport_handler.js";
17
+ export { A2AExpressApp } from "./server/a2a_express_app.js";
18
+ export { A2AError } from "./server/error.js";
19
+ export { A2AClient } from "./client/client.js";
20
+ export * from "./types.js";
21
+ export type { A2AResponse } from "./a2a_response.js";
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Main entry point for the A2A Server V2 library.
3
+ * Exports the server class, store implementations, and core types.
4
+ */
5
+ export { RequestContext } from "./server/agent_execution/request_context.js";
6
+ export { DefaultExecutionEventBus } from "./server/events/execution_event_bus.js";
7
+ export { DefaultExecutionEventBusManager } from "./server/events/execution_event_bus_manager.js";
8
+ export { DefaultRequestHandler } from "./server/request_handler/default_request_handler.js";
9
+ export { ResultManager } from "./server/result_manager.js";
10
+ export { InMemoryTaskStore } from "./server/store.js";
11
+ export { JsonRpcTransportHandler } from "./server/transports/jsonrpc_transport_handler.js";
12
+ export { A2AExpressApp } from "./server/a2a_express_app.js";
13
+ export { A2AError } from "./server/error.js";
14
+ // Export Client
15
+ export { A2AClient } from "./client/client.js";
16
+ // Re-export all schema types for convenience
17
+ export * from "./types.js";
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ export declare const ai: import("genkit").Genkit;
2
+ export { z } from "genkit";
@@ -0,0 +1,11 @@
1
+ import { googleAI } from "@genkit-ai/googleai";
2
+ import { genkit } from "genkit";
3
+ import { dirname } from "path";
4
+ import { fileURLToPath } from "url";
5
+ export const ai = genkit({
6
+ plugins: [googleAI()],
7
+ model: googleAI.model("gemini-2.0-flash"),
8
+ promptDir: dirname(fileURLToPath(import.meta.url)),
9
+ });
10
+ export { z } from "genkit";
11
+ //# sourceMappingURL=genkit.js.map
@@ -0,0 +1 @@
1
+ export {};