@a2a-js/sdk 0.2.3 → 0.2.4

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.
@@ -0,0 +1,396 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/client/index.ts
20
+ var client_exports = {};
21
+ __export(client_exports, {
22
+ A2AClient: () => A2AClient
23
+ });
24
+ module.exports = __toCommonJS(client_exports);
25
+
26
+ // src/client/client.ts
27
+ var A2AClient = class {
28
+ agentBaseUrl;
29
+ agentCardPromise;
30
+ requestIdCounter = 1;
31
+ serviceEndpointUrl;
32
+ // To be populated from AgentCard after fetching
33
+ /**
34
+ * Constructs an A2AClient instance.
35
+ * It initiates fetching the agent card from the provided agent baseUrl.
36
+ * The Agent Card is expected at `${agentBaseUrl}/.well-known/agent.json`.
37
+ * The `url` field from the Agent Card will be used as the RPC service endpoint.
38
+ * @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com).
39
+ */
40
+ constructor(agentBaseUrl) {
41
+ this.agentBaseUrl = agentBaseUrl.replace(/\/$/, "");
42
+ this.agentCardPromise = this._fetchAndCacheAgentCard();
43
+ }
44
+ /**
45
+ * Fetches the Agent Card from the agent's well-known URI and caches its service endpoint URL.
46
+ * This method is called by the constructor.
47
+ * @returns A Promise that resolves to the AgentCard.
48
+ */
49
+ async _fetchAndCacheAgentCard() {
50
+ const agentCardUrl = `${this.agentBaseUrl}/.well-known/agent.json`;
51
+ try {
52
+ const response = await fetch(agentCardUrl, {
53
+ headers: { "Accept": "application/json" }
54
+ });
55
+ if (!response.ok) {
56
+ throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`);
57
+ }
58
+ const agentCard = await response.json();
59
+ if (!agentCard.url) {
60
+ throw new Error("Fetched Agent Card does not contain a valid 'url' for the service endpoint.");
61
+ }
62
+ this.serviceEndpointUrl = agentCard.url;
63
+ return agentCard;
64
+ } catch (error) {
65
+ console.error("Error fetching or parsing Agent Card:");
66
+ throw error;
67
+ }
68
+ }
69
+ /**
70
+ * Retrieves the Agent Card.
71
+ * If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
72
+ * Otherwise, it returns the card fetched and cached during client construction.
73
+ * @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
74
+ * If provided, this will fetch a new card, not use the cached one from the constructor's URL.
75
+ * @returns A Promise that resolves to the AgentCard.
76
+ */
77
+ async getAgentCard(agentBaseUrl) {
78
+ if (agentBaseUrl) {
79
+ const specificAgentBaseUrl = agentBaseUrl.replace(/\/$/, "");
80
+ const agentCardUrl = `${specificAgentBaseUrl}/.well-known/agent.json`;
81
+ const response = await fetch(agentCardUrl, {
82
+ headers: { "Accept": "application/json" }
83
+ });
84
+ if (!response.ok) {
85
+ throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`);
86
+ }
87
+ return await response.json();
88
+ }
89
+ return this.agentCardPromise;
90
+ }
91
+ /**
92
+ * Gets the RPC service endpoint URL. Ensures the agent card has been fetched first.
93
+ * @returns A Promise that resolves to the service endpoint URL string.
94
+ */
95
+ async _getServiceEndpoint() {
96
+ if (this.serviceEndpointUrl) {
97
+ return this.serviceEndpointUrl;
98
+ }
99
+ await this.agentCardPromise;
100
+ if (!this.serviceEndpointUrl) {
101
+ throw new Error("Agent Card URL for RPC endpoint is not available. Fetching might have failed.");
102
+ }
103
+ return this.serviceEndpointUrl;
104
+ }
105
+ /**
106
+ * Helper method to make a generic JSON-RPC POST request.
107
+ * @param method The RPC method name.
108
+ * @param params The parameters for the RPC method.
109
+ * @returns A Promise that resolves to the RPC response.
110
+ */
111
+ async _postRpcRequest(method, params) {
112
+ const endpoint = await this._getServiceEndpoint();
113
+ const requestId = this.requestIdCounter++;
114
+ const rpcRequest = {
115
+ jsonrpc: "2.0",
116
+ method,
117
+ params,
118
+ // Cast because TParams structure varies per method
119
+ id: requestId
120
+ };
121
+ const httpResponse = await fetch(endpoint, {
122
+ method: "POST",
123
+ headers: {
124
+ "Content-Type": "application/json",
125
+ "Accept": "application/json"
126
+ // Expect JSON response for non-streaming requests
127
+ },
128
+ body: JSON.stringify(rpcRequest)
129
+ });
130
+ if (!httpResponse.ok) {
131
+ let errorBodyText = "(empty or non-JSON response)";
132
+ try {
133
+ errorBodyText = await httpResponse.text();
134
+ const errorJson = JSON.parse(errorBodyText);
135
+ if (!errorJson.jsonrpc && errorJson.error) {
136
+ throw new Error(`RPC error for ${method}: ${errorJson.error.message} (Code: ${errorJson.error.code}, HTTP Status: ${httpResponse.status}) Data: ${JSON.stringify(errorJson.error.data)}`);
137
+ } else if (!errorJson.jsonrpc) {
138
+ throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
139
+ }
140
+ } catch (e) {
141
+ if (e.message.startsWith("RPC error for") || e.message.startsWith("HTTP error for")) throw e;
142
+ throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
143
+ }
144
+ }
145
+ const rpcResponse = await httpResponse.json();
146
+ if (rpcResponse.id !== requestId) {
147
+ console.error(`CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}. This may lead to incorrect response handling.`);
148
+ }
149
+ return rpcResponse;
150
+ }
151
+ /**
152
+ * Sends a message to the agent.
153
+ * The behavior (blocking/non-blocking) and push notification configuration
154
+ * are specified within the `params.configuration` object.
155
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
156
+ * @param params The parameters for sending the message, including the message content and configuration.
157
+ * @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
158
+ */
159
+ async sendMessage(params) {
160
+ return this._postRpcRequest("message/send", params);
161
+ }
162
+ /**
163
+ * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
164
+ * Push notification configuration can be specified in `params.configuration`.
165
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
166
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
167
+ * @param params The parameters for sending the message.
168
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
169
+ * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
170
+ */
171
+ async *sendMessageStream(params) {
172
+ const agentCard = await this.agentCardPromise;
173
+ if (!agentCard.capabilities?.streaming) {
174
+ throw new Error("Agent does not support streaming (AgentCard.capabilities.streaming is not true).");
175
+ }
176
+ const endpoint = await this._getServiceEndpoint();
177
+ const clientRequestId = this.requestIdCounter++;
178
+ const rpcRequest = {
179
+ // This is the initial JSON-RPC request to establish the stream
180
+ jsonrpc: "2.0",
181
+ method: "message/stream",
182
+ params,
183
+ id: clientRequestId
184
+ };
185
+ const response = await fetch(endpoint, {
186
+ method: "POST",
187
+ headers: {
188
+ "Content-Type": "application/json",
189
+ "Accept": "text/event-stream"
190
+ // Crucial for SSE
191
+ },
192
+ body: JSON.stringify(rpcRequest)
193
+ });
194
+ if (!response.ok) {
195
+ let errorBody = "";
196
+ try {
197
+ errorBody = await response.text();
198
+ const errorJson = JSON.parse(errorBody);
199
+ if (errorJson.error) {
200
+ throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
201
+ }
202
+ } catch (e) {
203
+ if (e.message.startsWith("HTTP error establishing stream")) throw e;
204
+ throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. Response: ${errorBody || "(empty)"}`);
205
+ }
206
+ throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}`);
207
+ }
208
+ if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
209
+ throw new Error("Invalid response Content-Type for SSE stream. Expected 'text/event-stream'.");
210
+ }
211
+ yield* this._parseA2ASseStream(response, clientRequestId);
212
+ }
213
+ /**
214
+ * Sets or updates the push notification configuration for a given task.
215
+ * Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
216
+ * @param params Parameters containing the taskId and the TaskPushNotificationConfig.
217
+ * @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
218
+ */
219
+ async setTaskPushNotificationConfig(params) {
220
+ const agentCard = await this.agentCardPromise;
221
+ if (!agentCard.capabilities?.pushNotifications) {
222
+ throw new Error("Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true).");
223
+ }
224
+ return this._postRpcRequest(
225
+ "tasks/pushNotificationConfig/set",
226
+ params
227
+ );
228
+ }
229
+ /**
230
+ * Gets the push notification configuration for a given task.
231
+ * @param params Parameters containing the taskId.
232
+ * @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
233
+ */
234
+ async getTaskPushNotificationConfig(params) {
235
+ return this._postRpcRequest(
236
+ "tasks/pushNotificationConfig/get",
237
+ params
238
+ );
239
+ }
240
+ /**
241
+ * Retrieves a task by its ID.
242
+ * @param params Parameters containing the taskId and optional historyLength.
243
+ * @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
244
+ */
245
+ async getTask(params) {
246
+ return this._postRpcRequest("tasks/get", params);
247
+ }
248
+ /**
249
+ * Cancels a task by its ID.
250
+ * @param params Parameters containing the taskId.
251
+ * @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
252
+ */
253
+ async cancelTask(params) {
254
+ return this._postRpcRequest("tasks/cancel", params);
255
+ }
256
+ /**
257
+ * Resubscribes to a task's event stream using Server-Sent Events (SSE).
258
+ * This is used if a previous SSE connection for an active task was broken.
259
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
260
+ * @param params Parameters containing the taskId.
261
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
262
+ */
263
+ async *resubscribeTask(params) {
264
+ const agentCard = await this.agentCardPromise;
265
+ if (!agentCard.capabilities?.streaming) {
266
+ throw new Error("Agent does not support streaming (required for tasks/resubscribe).");
267
+ }
268
+ const endpoint = await this._getServiceEndpoint();
269
+ const clientRequestId = this.requestIdCounter++;
270
+ const rpcRequest = {
271
+ // Initial JSON-RPC request to establish the stream
272
+ jsonrpc: "2.0",
273
+ method: "tasks/resubscribe",
274
+ params,
275
+ id: clientRequestId
276
+ };
277
+ const response = await fetch(endpoint, {
278
+ method: "POST",
279
+ headers: {
280
+ "Content-Type": "application/json",
281
+ "Accept": "text/event-stream"
282
+ },
283
+ body: JSON.stringify(rpcRequest)
284
+ });
285
+ if (!response.ok) {
286
+ let errorBody = "";
287
+ try {
288
+ errorBody = await response.text();
289
+ const errorJson = JSON.parse(errorBody);
290
+ if (errorJson.error) {
291
+ throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
292
+ }
293
+ } catch (e) {
294
+ if (e.message.startsWith("HTTP error establishing stream")) throw e;
295
+ throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. Response: ${errorBody || "(empty)"}`);
296
+ }
297
+ throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}`);
298
+ }
299
+ if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
300
+ throw new Error("Invalid response Content-Type for SSE stream on resubscribe. Expected 'text/event-stream'.");
301
+ }
302
+ yield* this._parseA2ASseStream(response, clientRequestId);
303
+ }
304
+ /**
305
+ * Parses an HTTP response body as an A2A Server-Sent Event stream.
306
+ * Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,
307
+ * specifically a SendStreamingMessageResponse (or similar structure for resubscribe).
308
+ * @param response The HTTP Response object whose body is the SSE stream.
309
+ * @param originalRequestId The ID of the client's JSON-RPC request that initiated this stream.
310
+ * Used to validate the `id` in the streamed JSON-RPC responses.
311
+ * @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.
312
+ */
313
+ async *_parseA2ASseStream(response, originalRequestId) {
314
+ if (!response.body) {
315
+ throw new Error("SSE response body is undefined. Cannot read stream.");
316
+ }
317
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
318
+ let buffer = "";
319
+ let eventDataBuffer = "";
320
+ try {
321
+ while (true) {
322
+ const { done, value } = await reader.read();
323
+ if (done) {
324
+ if (eventDataBuffer.trim()) {
325
+ const result = this._processSseEventData(eventDataBuffer, originalRequestId);
326
+ yield result;
327
+ }
328
+ break;
329
+ }
330
+ buffer += value;
331
+ let lineEndIndex;
332
+ while ((lineEndIndex = buffer.indexOf("\n")) >= 0) {
333
+ const line = buffer.substring(0, lineEndIndex).trim();
334
+ buffer = buffer.substring(lineEndIndex + 1);
335
+ if (line === "") {
336
+ if (eventDataBuffer) {
337
+ const result = this._processSseEventData(eventDataBuffer, originalRequestId);
338
+ yield result;
339
+ eventDataBuffer = "";
340
+ }
341
+ } else if (line.startsWith("data:")) {
342
+ eventDataBuffer += line.substring(5).trimStart() + "\n";
343
+ } else if (line.startsWith(":")) {
344
+ } else if (line.includes(":")) {
345
+ }
346
+ }
347
+ }
348
+ } catch (error) {
349
+ console.error("Error reading or parsing SSE stream:", error.message);
350
+ throw error;
351
+ } finally {
352
+ reader.releaseLock();
353
+ }
354
+ }
355
+ /**
356
+ * Processes a single SSE event's data string, expecting it to be a JSON-RPC response.
357
+ * @param jsonData The string content from one or more 'data:' lines of an SSE event.
358
+ * @param originalRequestId The ID of the client's request that initiated the stream.
359
+ * @returns The `result` field of the parsed JSON-RPC success response.
360
+ * @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.
361
+ */
362
+ _processSseEventData(jsonData, originalRequestId) {
363
+ if (!jsonData.trim()) {
364
+ throw new Error("Attempted to process empty SSE event data.");
365
+ }
366
+ try {
367
+ const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\n$/, ""));
368
+ const a2aStreamResponse = sseJsonRpcResponse;
369
+ if (a2aStreamResponse.id !== originalRequestId) {
370
+ console.warn(`SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`);
371
+ }
372
+ if (this.isErrorResponse(a2aStreamResponse)) {
373
+ const err = a2aStreamResponse.error;
374
+ throw new Error(`SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data)}`);
375
+ }
376
+ if (!("result" in a2aStreamResponse) || typeof a2aStreamResponse.result === "undefined") {
377
+ throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
378
+ }
379
+ const successResponse = a2aStreamResponse;
380
+ return successResponse.result;
381
+ } catch (e) {
382
+ if (e.message.startsWith("SSE event contained an error") || e.message.startsWith("SSE event JSON-RPC response is missing 'result' field")) {
383
+ throw e;
384
+ }
385
+ console.error("Failed to parse SSE event data string or unexpected JSON-RPC structure:", jsonData, e);
386
+ throw new Error(`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${e.message}`);
387
+ }
388
+ }
389
+ isErrorResponse(response) {
390
+ return "error" in response;
391
+ }
392
+ };
393
+ // Annotate the CommonJS export names for ESM import in node:
394
+ 0 && (module.exports = {
395
+ A2AClient
396
+ });
@@ -0,0 +1,120 @@
1
+ import { A as AgentCard, M as MessageSendParams, S as SendMessageResponse, a as Message, T as Task, b as TaskStatusUpdateEvent, c as TaskArtifactUpdateEvent, d as TaskPushNotificationConfig, e as SetTaskPushNotificationConfigResponse, f as TaskIdParams, G as GetTaskPushNotificationConfigResponse, g as TaskQueryParams, h as GetTaskResponse, C as CancelTaskResponse, J as JSONRPCResponse, i as JSONRPCErrorResponse } from '../types-CcBgkR2G.cjs';
2
+
3
+ type A2AStreamEventData = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
4
+ /**
5
+ * A2AClient is a TypeScript HTTP client for interacting with A2A-compliant agents.
6
+ */
7
+ declare class A2AClient {
8
+ private agentBaseUrl;
9
+ private agentCardPromise;
10
+ private requestIdCounter;
11
+ private serviceEndpointUrl?;
12
+ /**
13
+ * Constructs an A2AClient instance.
14
+ * It initiates fetching the agent card from the provided agent baseUrl.
15
+ * The Agent Card is expected at `${agentBaseUrl}/.well-known/agent.json`.
16
+ * The `url` field from the Agent Card will be used as the RPC service endpoint.
17
+ * @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com).
18
+ */
19
+ constructor(agentBaseUrl: string);
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
+ private _fetchAndCacheAgentCard;
26
+ /**
27
+ * Retrieves the Agent Card.
28
+ * If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
29
+ * Otherwise, it returns the card fetched and cached during client construction.
30
+ * @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
31
+ * If provided, this will fetch a new card, not use the cached one from the constructor's URL.
32
+ * @returns A Promise that resolves to the AgentCard.
33
+ */
34
+ getAgentCard(agentBaseUrl?: string): Promise<AgentCard>;
35
+ /**
36
+ * Gets the RPC service endpoint URL. Ensures the agent card has been fetched first.
37
+ * @returns A Promise that resolves to the service endpoint URL string.
38
+ */
39
+ private _getServiceEndpoint;
40
+ /**
41
+ * Helper method to make a generic JSON-RPC POST request.
42
+ * @param method The RPC method name.
43
+ * @param params The parameters for the RPC method.
44
+ * @returns A Promise that resolves to the RPC response.
45
+ */
46
+ private _postRpcRequest;
47
+ /**
48
+ * Sends a message to the agent.
49
+ * The behavior (blocking/non-blocking) and push notification configuration
50
+ * are specified within the `params.configuration` object.
51
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
52
+ * @param params The parameters for sending the message, including the message content and configuration.
53
+ * @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
54
+ */
55
+ sendMessage(params: MessageSendParams): Promise<SendMessageResponse>;
56
+ /**
57
+ * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
58
+ * Push notification configuration can be specified in `params.configuration`.
59
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
60
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
61
+ * @param params The parameters for sending the message.
62
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
63
+ * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
64
+ */
65
+ sendMessageStream(params: MessageSendParams): AsyncGenerator<A2AStreamEventData, void, undefined>;
66
+ /**
67
+ * Sets or updates the push notification configuration for a given task.
68
+ * Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
69
+ * @param params Parameters containing the taskId and the TaskPushNotificationConfig.
70
+ * @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
71
+ */
72
+ setTaskPushNotificationConfig(params: TaskPushNotificationConfig): Promise<SetTaskPushNotificationConfigResponse>;
73
+ /**
74
+ * Gets the push notification configuration for a given task.
75
+ * @param params Parameters containing the taskId.
76
+ * @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
77
+ */
78
+ getTaskPushNotificationConfig(params: TaskIdParams): Promise<GetTaskPushNotificationConfigResponse>;
79
+ /**
80
+ * Retrieves a task by its ID.
81
+ * @param params Parameters containing the taskId and optional historyLength.
82
+ * @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
83
+ */
84
+ getTask(params: TaskQueryParams): Promise<GetTaskResponse>;
85
+ /**
86
+ * Cancels a task by its ID.
87
+ * @param params Parameters containing the taskId.
88
+ * @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
89
+ */
90
+ cancelTask(params: TaskIdParams): Promise<CancelTaskResponse>;
91
+ /**
92
+ * Resubscribes to a task's event stream using Server-Sent Events (SSE).
93
+ * This is used if a previous SSE connection for an active task was broken.
94
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
95
+ * @param params Parameters containing the taskId.
96
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
97
+ */
98
+ resubscribeTask(params: TaskIdParams): AsyncGenerator<A2AStreamEventData, void, undefined>;
99
+ /**
100
+ * Parses an HTTP response body as an A2A Server-Sent Event stream.
101
+ * Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,
102
+ * specifically a SendStreamingMessageResponse (or similar structure for resubscribe).
103
+ * @param response The HTTP Response object whose body is the SSE stream.
104
+ * @param originalRequestId The ID of the client's JSON-RPC request that initiated this stream.
105
+ * Used to validate the `id` in the streamed JSON-RPC responses.
106
+ * @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.
107
+ */
108
+ private _parseA2ASseStream;
109
+ /**
110
+ * Processes a single SSE event's data string, expecting it to be a JSON-RPC response.
111
+ * @param jsonData The string content from one or more 'data:' lines of an SSE event.
112
+ * @param originalRequestId The ID of the client's request that initiated the stream.
113
+ * @returns The `result` field of the parsed JSON-RPC success response.
114
+ * @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.
115
+ */
116
+ private _processSseEventData;
117
+ isErrorResponse(response: JSONRPCResponse): response is JSONRPCErrorResponse;
118
+ }
119
+
120
+ export { A2AClient };
@@ -0,0 +1,120 @@
1
+ import { A as AgentCard, M as MessageSendParams, S as SendMessageResponse, a as Message, T as Task, b as TaskStatusUpdateEvent, c as TaskArtifactUpdateEvent, d as TaskPushNotificationConfig, e as SetTaskPushNotificationConfigResponse, f as TaskIdParams, G as GetTaskPushNotificationConfigResponse, g as TaskQueryParams, h as GetTaskResponse, C as CancelTaskResponse, J as JSONRPCResponse, i as JSONRPCErrorResponse } from '../types-CcBgkR2G.js';
2
+
3
+ type A2AStreamEventData = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
4
+ /**
5
+ * A2AClient is a TypeScript HTTP client for interacting with A2A-compliant agents.
6
+ */
7
+ declare class A2AClient {
8
+ private agentBaseUrl;
9
+ private agentCardPromise;
10
+ private requestIdCounter;
11
+ private serviceEndpointUrl?;
12
+ /**
13
+ * Constructs an A2AClient instance.
14
+ * It initiates fetching the agent card from the provided agent baseUrl.
15
+ * The Agent Card is expected at `${agentBaseUrl}/.well-known/agent.json`.
16
+ * The `url` field from the Agent Card will be used as the RPC service endpoint.
17
+ * @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com).
18
+ */
19
+ constructor(agentBaseUrl: string);
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
+ private _fetchAndCacheAgentCard;
26
+ /**
27
+ * Retrieves the Agent Card.
28
+ * If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
29
+ * Otherwise, it returns the card fetched and cached during client construction.
30
+ * @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
31
+ * If provided, this will fetch a new card, not use the cached one from the constructor's URL.
32
+ * @returns A Promise that resolves to the AgentCard.
33
+ */
34
+ getAgentCard(agentBaseUrl?: string): Promise<AgentCard>;
35
+ /**
36
+ * Gets the RPC service endpoint URL. Ensures the agent card has been fetched first.
37
+ * @returns A Promise that resolves to the service endpoint URL string.
38
+ */
39
+ private _getServiceEndpoint;
40
+ /**
41
+ * Helper method to make a generic JSON-RPC POST request.
42
+ * @param method The RPC method name.
43
+ * @param params The parameters for the RPC method.
44
+ * @returns A Promise that resolves to the RPC response.
45
+ */
46
+ private _postRpcRequest;
47
+ /**
48
+ * Sends a message to the agent.
49
+ * The behavior (blocking/non-blocking) and push notification configuration
50
+ * are specified within the `params.configuration` object.
51
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
52
+ * @param params The parameters for sending the message, including the message content and configuration.
53
+ * @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
54
+ */
55
+ sendMessage(params: MessageSendParams): Promise<SendMessageResponse>;
56
+ /**
57
+ * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
58
+ * Push notification configuration can be specified in `params.configuration`.
59
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
60
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
61
+ * @param params The parameters for sending the message.
62
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
63
+ * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
64
+ */
65
+ sendMessageStream(params: MessageSendParams): AsyncGenerator<A2AStreamEventData, void, undefined>;
66
+ /**
67
+ * Sets or updates the push notification configuration for a given task.
68
+ * Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
69
+ * @param params Parameters containing the taskId and the TaskPushNotificationConfig.
70
+ * @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
71
+ */
72
+ setTaskPushNotificationConfig(params: TaskPushNotificationConfig): Promise<SetTaskPushNotificationConfigResponse>;
73
+ /**
74
+ * Gets the push notification configuration for a given task.
75
+ * @param params Parameters containing the taskId.
76
+ * @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
77
+ */
78
+ getTaskPushNotificationConfig(params: TaskIdParams): Promise<GetTaskPushNotificationConfigResponse>;
79
+ /**
80
+ * Retrieves a task by its ID.
81
+ * @param params Parameters containing the taskId and optional historyLength.
82
+ * @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
83
+ */
84
+ getTask(params: TaskQueryParams): Promise<GetTaskResponse>;
85
+ /**
86
+ * Cancels a task by its ID.
87
+ * @param params Parameters containing the taskId.
88
+ * @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
89
+ */
90
+ cancelTask(params: TaskIdParams): Promise<CancelTaskResponse>;
91
+ /**
92
+ * Resubscribes to a task's event stream using Server-Sent Events (SSE).
93
+ * This is used if a previous SSE connection for an active task was broken.
94
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
95
+ * @param params Parameters containing the taskId.
96
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
97
+ */
98
+ resubscribeTask(params: TaskIdParams): AsyncGenerator<A2AStreamEventData, void, undefined>;
99
+ /**
100
+ * Parses an HTTP response body as an A2A Server-Sent Event stream.
101
+ * Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,
102
+ * specifically a SendStreamingMessageResponse (or similar structure for resubscribe).
103
+ * @param response The HTTP Response object whose body is the SSE stream.
104
+ * @param originalRequestId The ID of the client's JSON-RPC request that initiated this stream.
105
+ * Used to validate the `id` in the streamed JSON-RPC responses.
106
+ * @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.
107
+ */
108
+ private _parseA2ASseStream;
109
+ /**
110
+ * Processes a single SSE event's data string, expecting it to be a JSON-RPC response.
111
+ * @param jsonData The string content from one or more 'data:' lines of an SSE event.
112
+ * @param originalRequestId The ID of the client's request that initiated the stream.
113
+ * @returns The `result` field of the parsed JSON-RPC success response.
114
+ * @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.
115
+ */
116
+ private _processSseEventData;
117
+ isErrorResponse(response: JSONRPCResponse): response is JSONRPCErrorResponse;
118
+ }
119
+
120
+ export { A2AClient };