@mailmodo/a2a 0.3.3 → 0.3.7

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,1605 @@
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
+ AgentCardResolver: () => AgentCardResolver,
24
+ AuthenticatedExtendedCardNotConfiguredError: () => AuthenticatedExtendedCardNotConfiguredError,
25
+ Client: () => Client,
26
+ ClientCallContext: () => ClientCallContext,
27
+ ClientCallContextKey: () => ClientCallContextKey,
28
+ ClientFactory: () => ClientFactory,
29
+ ClientFactoryOptions: () => ClientFactoryOptions,
30
+ ContentTypeNotSupportedError: () => ContentTypeNotSupportedError,
31
+ DefaultAgentCardResolver: () => DefaultAgentCardResolver,
32
+ InvalidAgentResponseError: () => InvalidAgentResponseError,
33
+ JsonRpcTransport: () => JsonRpcTransport,
34
+ JsonRpcTransportFactory: () => JsonRpcTransportFactory,
35
+ PushNotificationNotSupportedError: () => PushNotificationNotSupportedError,
36
+ RestTransport: () => RestTransport,
37
+ RestTransportFactory: () => RestTransportFactory,
38
+ ServiceParameters: () => ServiceParameters,
39
+ TaskNotCancelableError: () => TaskNotCancelableError,
40
+ TaskNotFoundError: () => TaskNotFoundError,
41
+ UnsupportedOperationError: () => UnsupportedOperationError,
42
+ createAuthenticatingFetchWithRetry: () => createAuthenticatingFetchWithRetry,
43
+ withA2AExtensions: () => withA2AExtensions
44
+ });
45
+ module.exports = __toCommonJS(client_exports);
46
+
47
+ // src/constants.ts
48
+ var AGENT_CARD_PATH = ".well-known/agent-card.json";
49
+ var HTTP_EXTENSION_HEADER = "X-A2A-Extensions";
50
+
51
+ // src/errors.ts
52
+ var A2A_ERROR_CODE = {
53
+ PARSE_ERROR: -32700,
54
+ INVALID_REQUEST: -32600,
55
+ METHOD_NOT_FOUND: -32601,
56
+ INVALID_PARAMS: -32602,
57
+ INTERNAL_ERROR: -32603,
58
+ TASK_NOT_FOUND: -32001,
59
+ TASK_NOT_CANCELABLE: -32002,
60
+ PUSH_NOTIFICATION_NOT_SUPPORTED: -32003,
61
+ UNSUPPORTED_OPERATION: -32004,
62
+ CONTENT_TYPE_NOT_SUPPORTED: -32005,
63
+ INVALID_AGENT_RESPONSE: -32006,
64
+ AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED: -32007
65
+ };
66
+ var TaskNotFoundError = class extends Error {
67
+ constructor(message) {
68
+ super(message ?? "Task not found");
69
+ this.name = "TaskNotFoundError";
70
+ }
71
+ };
72
+ var TaskNotCancelableError = class extends Error {
73
+ constructor(message) {
74
+ super(message ?? "Task cannot be canceled");
75
+ this.name = "TaskNotCancelableError";
76
+ }
77
+ };
78
+ var PushNotificationNotSupportedError = class extends Error {
79
+ constructor(message) {
80
+ super(message ?? "Push Notification is not supported");
81
+ this.name = "PushNotificationNotSupportedError";
82
+ }
83
+ };
84
+ var UnsupportedOperationError = class extends Error {
85
+ constructor(message) {
86
+ super(message ?? "This operation is not supported");
87
+ this.name = "UnsupportedOperationError";
88
+ }
89
+ };
90
+ var ContentTypeNotSupportedError = class extends Error {
91
+ constructor(message) {
92
+ super(message ?? "Incompatible content types");
93
+ this.name = "ContentTypeNotSupportedError";
94
+ }
95
+ };
96
+ var InvalidAgentResponseError = class extends Error {
97
+ constructor(message) {
98
+ super(message ?? "Invalid agent response type");
99
+ this.name = "InvalidAgentResponseError";
100
+ }
101
+ };
102
+ var AuthenticatedExtendedCardNotConfiguredError = class extends Error {
103
+ constructor(message) {
104
+ super(message ?? "Authenticated Extended Card not configured");
105
+ this.name = "AuthenticatedExtendedCardNotConfiguredError";
106
+ }
107
+ };
108
+
109
+ // src/sse_utils.ts
110
+ async function* parseSseStream(response) {
111
+ if (!response.body) {
112
+ throw new Error("SSE response body is undefined. Cannot read stream.");
113
+ }
114
+ let buffer = "";
115
+ let eventType = "message";
116
+ let eventData = "";
117
+ for await (const value of response.body.pipeThrough(new TextDecoderStream())) {
118
+ buffer += value;
119
+ let lineEndIndex;
120
+ while ((lineEndIndex = buffer.indexOf("\n")) >= 0) {
121
+ const line = buffer.substring(0, lineEndIndex).trim();
122
+ buffer = buffer.substring(lineEndIndex + 1);
123
+ if (line === "") {
124
+ if (eventData) {
125
+ yield { type: eventType, data: eventData };
126
+ eventData = "";
127
+ eventType = "message";
128
+ }
129
+ } else if (line.startsWith("event:")) {
130
+ eventType = line.substring("event:".length).trim();
131
+ } else if (line.startsWith("data:")) {
132
+ eventData = line.substring("data:".length).trim();
133
+ }
134
+ }
135
+ }
136
+ if (eventData) {
137
+ yield { type: eventType, data: eventData };
138
+ }
139
+ }
140
+
141
+ // src/client/transports/json_rpc_transport.ts
142
+ var JsonRpcTransport = class _JsonRpcTransport {
143
+ customFetchImpl;
144
+ endpoint;
145
+ requestIdCounter = 1;
146
+ constructor(options) {
147
+ this.endpoint = options.endpoint;
148
+ this.customFetchImpl = options.fetchImpl;
149
+ }
150
+ async getExtendedAgentCard(options, idOverride) {
151
+ const rpcResponse = await this._sendRpcRequest("agent/getAuthenticatedExtendedCard", void 0, idOverride, options);
152
+ return rpcResponse.result;
153
+ }
154
+ async sendMessage(params, options, idOverride) {
155
+ const rpcResponse = await this._sendRpcRequest(
156
+ "message/send",
157
+ params,
158
+ idOverride,
159
+ options
160
+ );
161
+ return rpcResponse.result;
162
+ }
163
+ async *sendMessageStream(params, options) {
164
+ yield* this._sendStreamingRequest("message/stream", params, options);
165
+ }
166
+ async setTaskPushNotificationConfig(params, options, idOverride) {
167
+ const rpcResponse = await this._sendRpcRequest("tasks/pushNotificationConfig/set", params, idOverride, options);
168
+ return rpcResponse.result;
169
+ }
170
+ async getTaskPushNotificationConfig(params, options, idOverride) {
171
+ const rpcResponse = await this._sendRpcRequest("tasks/pushNotificationConfig/get", params, idOverride, options);
172
+ return rpcResponse.result;
173
+ }
174
+ async listTaskPushNotificationConfig(params, options, idOverride) {
175
+ const rpcResponse = await this._sendRpcRequest("tasks/pushNotificationConfig/list", params, idOverride, options);
176
+ return rpcResponse.result;
177
+ }
178
+ async deleteTaskPushNotificationConfig(params, options, idOverride) {
179
+ await this._sendRpcRequest("tasks/pushNotificationConfig/delete", params, idOverride, options);
180
+ }
181
+ async getTask(params, options, idOverride) {
182
+ const rpcResponse = await this._sendRpcRequest(
183
+ "tasks/get",
184
+ params,
185
+ idOverride,
186
+ options
187
+ );
188
+ return rpcResponse.result;
189
+ }
190
+ async cancelTask(params, options, idOverride) {
191
+ const rpcResponse = await this._sendRpcRequest(
192
+ "tasks/cancel",
193
+ params,
194
+ idOverride,
195
+ options
196
+ );
197
+ return rpcResponse.result;
198
+ }
199
+ async *resubscribeTask(params, options) {
200
+ yield* this._sendStreamingRequest("tasks/resubscribe", params, options);
201
+ }
202
+ async callExtensionMethod(method, params, idOverride, options) {
203
+ return await this._sendRpcRequest(
204
+ method,
205
+ params,
206
+ idOverride,
207
+ options
208
+ );
209
+ }
210
+ _fetch(...args) {
211
+ if (this.customFetchImpl) {
212
+ return this.customFetchImpl(...args);
213
+ }
214
+ if (typeof fetch === "function") {
215
+ return fetch(...args);
216
+ }
217
+ throw new Error(
218
+ "A `fetch` implementation was not provided and is not available in the global scope. Please provide a `fetchImpl` in the A2ATransportOptions. "
219
+ );
220
+ }
221
+ async _sendRpcRequest(method, params, idOverride, options) {
222
+ const requestId = idOverride ?? this.requestIdCounter++;
223
+ const rpcRequest = {
224
+ jsonrpc: "2.0",
225
+ method,
226
+ params,
227
+ id: requestId
228
+ };
229
+ const httpResponse = await this._fetchRpc(rpcRequest, "application/json", options);
230
+ if (!httpResponse.ok) {
231
+ let errorBodyText = "(empty or non-JSON response)";
232
+ let errorJson;
233
+ try {
234
+ errorBodyText = await httpResponse.text();
235
+ errorJson = JSON.parse(errorBodyText);
236
+ } catch (e) {
237
+ throw new Error(
238
+ `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,
239
+ { cause: e }
240
+ );
241
+ }
242
+ if (errorJson.jsonrpc && errorJson.error) {
243
+ throw _JsonRpcTransport.mapToError(errorJson);
244
+ } else {
245
+ throw new Error(
246
+ `HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`
247
+ );
248
+ }
249
+ }
250
+ const rpcResponse = await httpResponse.json();
251
+ if (rpcResponse.id !== requestId) {
252
+ console.error(
253
+ `CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}.`
254
+ );
255
+ }
256
+ if ("error" in rpcResponse) {
257
+ throw _JsonRpcTransport.mapToError(rpcResponse);
258
+ }
259
+ return rpcResponse;
260
+ }
261
+ async _fetchRpc(rpcRequest, acceptHeader = "application/json", options) {
262
+ const requestInit = {
263
+ method: "POST",
264
+ headers: {
265
+ ...options?.serviceParameters,
266
+ "Content-Type": "application/json",
267
+ Accept: acceptHeader
268
+ },
269
+ body: JSON.stringify(rpcRequest),
270
+ signal: options?.signal
271
+ };
272
+ return this._fetch(this.endpoint, requestInit);
273
+ }
274
+ async *_sendStreamingRequest(method, params, options) {
275
+ const clientRequestId = this.requestIdCounter++;
276
+ const rpcRequest = {
277
+ jsonrpc: "2.0",
278
+ method,
279
+ params,
280
+ id: clientRequestId
281
+ };
282
+ const response = await this._fetchRpc(rpcRequest, "text/event-stream", options);
283
+ if (!response.ok) {
284
+ let errorBody = "";
285
+ let errorJson;
286
+ try {
287
+ errorBody = await response.text();
288
+ errorJson = JSON.parse(errorBody);
289
+ } catch (e) {
290
+ throw new Error(
291
+ `HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}. Response: ${errorBody || "(empty)"}`,
292
+ { cause: e }
293
+ );
294
+ }
295
+ if (errorJson.error) {
296
+ throw new Error(
297
+ `HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`
298
+ );
299
+ }
300
+ throw new Error(
301
+ `HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}`
302
+ );
303
+ }
304
+ if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
305
+ throw new Error(
306
+ `Invalid response Content-Type for SSE stream for ${method}. Expected 'text/event-stream'.`
307
+ );
308
+ }
309
+ for await (const event of parseSseStream(response)) {
310
+ yield this._processSseEventData(event.data, clientRequestId);
311
+ }
312
+ }
313
+ _processSseEventData(jsonData, originalRequestId) {
314
+ if (!jsonData.trim()) {
315
+ throw new Error("Attempted to process empty SSE event data.");
316
+ }
317
+ try {
318
+ const sseJsonRpcResponse = JSON.parse(jsonData);
319
+ const a2aStreamResponse = sseJsonRpcResponse;
320
+ if (a2aStreamResponse.id !== originalRequestId) {
321
+ console.warn(
322
+ `SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`
323
+ );
324
+ }
325
+ if ("error" in a2aStreamResponse) {
326
+ const err = a2aStreamResponse.error;
327
+ throw new Error(
328
+ `SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data || {})}`
329
+ );
330
+ }
331
+ if (!("result" in a2aStreamResponse) || typeof a2aStreamResponse.result === "undefined") {
332
+ throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
333
+ }
334
+ return a2aStreamResponse.result;
335
+ } catch (e) {
336
+ if (e instanceof Error && (e.message.startsWith("SSE event contained an error") || e.message.startsWith("SSE event JSON-RPC response is missing 'result' field"))) {
337
+ throw e;
338
+ }
339
+ console.error(
340
+ "Failed to parse SSE event data string or unexpected JSON-RPC structure:",
341
+ jsonData,
342
+ e
343
+ );
344
+ throw new Error(
345
+ `Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${e instanceof Error && e.message || "Unknown error"}`
346
+ );
347
+ }
348
+ }
349
+ static mapToError(response) {
350
+ switch (response.error.code) {
351
+ case -32001:
352
+ return new TaskNotFoundJSONRPCError(response);
353
+ case -32002:
354
+ return new TaskNotCancelableJSONRPCError(response);
355
+ case -32003:
356
+ return new PushNotificationNotSupportedJSONRPCError(response);
357
+ case -32004:
358
+ return new UnsupportedOperationJSONRPCError(response);
359
+ case -32005:
360
+ return new ContentTypeNotSupportedJSONRPCError(response);
361
+ case -32006:
362
+ return new InvalidAgentResponseJSONRPCError(response);
363
+ case -32007:
364
+ return new AuthenticatedExtendedCardNotConfiguredJSONRPCError(response);
365
+ default:
366
+ return new JSONRPCTransportError(response);
367
+ }
368
+ }
369
+ };
370
+ var JsonRpcTransportFactory = class _JsonRpcTransportFactory {
371
+ constructor(options) {
372
+ this.options = options;
373
+ }
374
+ static name = "JSONRPC";
375
+ get protocolName() {
376
+ return _JsonRpcTransportFactory.name;
377
+ }
378
+ async create(url, _agentCard) {
379
+ return new JsonRpcTransport({
380
+ endpoint: url,
381
+ fetchImpl: this.options?.fetchImpl
382
+ });
383
+ }
384
+ };
385
+ var JSONRPCTransportError = class extends Error {
386
+ constructor(errorResponse) {
387
+ super(
388
+ `JSON-RPC error: ${errorResponse.error.message} (Code: ${errorResponse.error.code}) Data: ${JSON.stringify(errorResponse.error.data || {})}`
389
+ );
390
+ this.errorResponse = errorResponse;
391
+ }
392
+ };
393
+ var TaskNotFoundJSONRPCError = class extends TaskNotFoundError {
394
+ constructor(errorResponse) {
395
+ super();
396
+ this.errorResponse = errorResponse;
397
+ }
398
+ };
399
+ var TaskNotCancelableJSONRPCError = class extends TaskNotCancelableError {
400
+ constructor(errorResponse) {
401
+ super();
402
+ this.errorResponse = errorResponse;
403
+ }
404
+ };
405
+ var PushNotificationNotSupportedJSONRPCError = class extends PushNotificationNotSupportedError {
406
+ constructor(errorResponse) {
407
+ super();
408
+ this.errorResponse = errorResponse;
409
+ }
410
+ };
411
+ var UnsupportedOperationJSONRPCError = class extends UnsupportedOperationError {
412
+ constructor(errorResponse) {
413
+ super();
414
+ this.errorResponse = errorResponse;
415
+ }
416
+ };
417
+ var ContentTypeNotSupportedJSONRPCError = class extends ContentTypeNotSupportedError {
418
+ constructor(errorResponse) {
419
+ super();
420
+ this.errorResponse = errorResponse;
421
+ }
422
+ };
423
+ var InvalidAgentResponseJSONRPCError = class extends InvalidAgentResponseError {
424
+ constructor(errorResponse) {
425
+ super();
426
+ this.errorResponse = errorResponse;
427
+ }
428
+ };
429
+ var AuthenticatedExtendedCardNotConfiguredJSONRPCError = class extends AuthenticatedExtendedCardNotConfiguredError {
430
+ constructor(errorResponse) {
431
+ super();
432
+ this.errorResponse = errorResponse;
433
+ }
434
+ };
435
+
436
+ // src/client/client.ts
437
+ var A2AClient = class _A2AClient {
438
+ static emptyOptions = void 0;
439
+ agentCardPromise;
440
+ customFetchImpl;
441
+ serviceEndpointUrl;
442
+ // To be populated from AgentCard after fetchin
443
+ // A2AClient is built around JSON-RPC types, so it will only support JSON-RPC transport, new client with transport agnostic interface is going to be created for multi-transport.
444
+ // New transport abstraction isn't going to expose individual transport specific fields, so to keep returning JSON-RPC IDs here for compatibility,
445
+ // keep counter here and pass it to JsonRpcTransport via an optional idOverride parameter (which is not visible via transport-agnostic A2ATransport interface).
446
+ transport;
447
+ requestIdCounter = 1;
448
+ /**
449
+ * Constructs an A2AClient instance from an AgentCard.
450
+ * @param agentCard The AgentCard object.
451
+ * @param options Optional. The options for the A2AClient including the fetch/auth implementation.
452
+ */
453
+ constructor(agentCard, options) {
454
+ this.customFetchImpl = options?.fetchImpl;
455
+ if (typeof agentCard === "string") {
456
+ console.warn(
457
+ "Warning: Constructing A2AClient with a URL is deprecated. Please use A2AClient.fromCardUrl() instead."
458
+ );
459
+ this.agentCardPromise = this._fetchAndCacheAgentCard(agentCard, options?.agentCardPath);
460
+ } else {
461
+ if (!agentCard.url) {
462
+ throw new Error(
463
+ "Provided Agent Card does not contain a valid 'url' for the service endpoint."
464
+ );
465
+ }
466
+ this.serviceEndpointUrl = agentCard.url;
467
+ this.agentCardPromise = Promise.resolve(agentCard);
468
+ }
469
+ }
470
+ /**
471
+ * Dynamically resolves the fetch implementation to use for requests.
472
+ * Prefers a custom implementation if provided, otherwise falls back to the global fetch.
473
+ * @returns The fetch implementation.
474
+ * @param args Arguments to pass to the fetch implementation.
475
+ * @throws If no fetch implementation is available.
476
+ */
477
+ _fetch(...args) {
478
+ if (this.customFetchImpl) {
479
+ return this.customFetchImpl(...args);
480
+ }
481
+ if (typeof fetch === "function") {
482
+ return fetch(...args);
483
+ }
484
+ throw new Error(
485
+ "A `fetch` implementation was not provided and is not available in the global scope. Please provide a `fetchImpl` in the A2AClientOptions. For earlier Node.js versions (pre-v18), you can use a library like `node-fetch`."
486
+ );
487
+ }
488
+ /**
489
+ * Creates an A2AClient instance by fetching the AgentCard from a URL then constructing the A2AClient.
490
+ * @param agentCardUrl The URL of the agent card.
491
+ * @param options Optional. The options for the A2AClient including the fetch/auth implementation.
492
+ * @returns A Promise that resolves to a new A2AClient instance.
493
+ */
494
+ static async fromCardUrl(agentCardUrl, options) {
495
+ const fetchImpl = options?.fetchImpl;
496
+ const requestInit = {
497
+ headers: { Accept: "application/json" }
498
+ };
499
+ let response;
500
+ if (fetchImpl) {
501
+ response = await fetchImpl(agentCardUrl, requestInit);
502
+ } else if (typeof fetch === "function") {
503
+ response = await fetch(agentCardUrl, requestInit);
504
+ } else {
505
+ throw new Error(
506
+ "A `fetch` implementation was not provided and is not available in the global scope. Please provide a `fetchImpl` in the A2AClientOptions. For earlier Node.js versions (pre-v18), you can use a library like `node-fetch`."
507
+ );
508
+ }
509
+ if (!response.ok) {
510
+ throw new Error(
511
+ `Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
512
+ );
513
+ }
514
+ let agentCard;
515
+ try {
516
+ agentCard = await response.json();
517
+ } catch (error) {
518
+ console.error("Failed to parse Agent Card JSON:", error);
519
+ throw new Error(
520
+ `Failed to parse Agent Card JSON from ${agentCardUrl}. Original error: ${error.message}`
521
+ );
522
+ }
523
+ return new _A2AClient(agentCard, options);
524
+ }
525
+ /**
526
+ * Sends a message to the agent.
527
+ * The behavior (blocking/non-blocking) and push notification configuration
528
+ * are specified within the `params.configuration` object.
529
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
530
+ * @param params The parameters for sending the message, including the message content and configuration.
531
+ * @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
532
+ */
533
+ async sendMessage(params) {
534
+ return await this.invokeJsonRpc(
535
+ (t, p, id) => t.sendMessage(p, _A2AClient.emptyOptions, id),
536
+ params
537
+ );
538
+ }
539
+ /**
540
+ * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
541
+ * Push notification configuration can be specified in `params.configuration`.
542
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
543
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
544
+ * @param params The parameters for sending the message.
545
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
546
+ * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
547
+ */
548
+ async *sendMessageStream(params) {
549
+ const agentCard = await this.agentCardPromise;
550
+ if (!agentCard.capabilities?.streaming) {
551
+ throw new Error(
552
+ "Agent does not support streaming (AgentCard.capabilities.streaming is not true)."
553
+ );
554
+ }
555
+ const transport = await this._getOrCreateTransport();
556
+ yield* transport.sendMessageStream(params);
557
+ }
558
+ /**
559
+ * Sets or updates the push notification configuration for a given task.
560
+ * Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
561
+ * @param params Parameters containing the taskId and the TaskPushNotificationConfig.
562
+ * @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
563
+ */
564
+ async setTaskPushNotificationConfig(params) {
565
+ const agentCard = await this.agentCardPromise;
566
+ if (!agentCard.capabilities?.pushNotifications) {
567
+ throw new Error(
568
+ "Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true)."
569
+ );
570
+ }
571
+ return await this.invokeJsonRpc((t, p, id) => t.setTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id), params);
572
+ }
573
+ /**
574
+ * Gets the push notification configuration for a given task.
575
+ * @param params Parameters containing the taskId.
576
+ * @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
577
+ */
578
+ async getTaskPushNotificationConfig(params) {
579
+ return await this.invokeJsonRpc(
580
+ (t, p, id) => t.getTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id),
581
+ params
582
+ );
583
+ }
584
+ /**
585
+ * Lists the push notification configurations for a given task.
586
+ * @param params Parameters containing the taskId.
587
+ * @returns A Promise resolving to ListTaskPushNotificationConfigResponse.
588
+ */
589
+ async listTaskPushNotificationConfig(params) {
590
+ return await this.invokeJsonRpc((t, p, id) => t.listTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id), params);
591
+ }
592
+ /**
593
+ * Deletes the push notification configuration for a given task.
594
+ * @param params Parameters containing the taskId and push notification configuration ID.
595
+ * @returns A Promise resolving to DeleteTaskPushNotificationConfigResponse.
596
+ */
597
+ async deleteTaskPushNotificationConfig(params) {
598
+ return await this.invokeJsonRpc((t, p, id) => t.deleteTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id), params);
599
+ }
600
+ /**
601
+ * Retrieves a task by its ID.
602
+ * @param params Parameters containing the taskId and optional historyLength.
603
+ * @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
604
+ */
605
+ async getTask(params) {
606
+ return await this.invokeJsonRpc(
607
+ (t, p, id) => t.getTask(p, _A2AClient.emptyOptions, id),
608
+ params
609
+ );
610
+ }
611
+ /**
612
+ * Cancels a task by its ID.
613
+ * @param params Parameters containing the taskId.
614
+ * @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
615
+ */
616
+ async cancelTask(params) {
617
+ return await this.invokeJsonRpc(
618
+ (t, p, id) => t.cancelTask(p, _A2AClient.emptyOptions, id),
619
+ params
620
+ );
621
+ }
622
+ /**
623
+ * @template TExtensionParams The type of parameters for the custom extension method.
624
+ * @template TExtensionResponse The type of response expected from the custom extension method.
625
+ * This should extend JSONRPCResponse. This ensures the extension response is still a valid A2A response.
626
+ * @param method Custom JSON-RPC method defined in the AgentCard's extensions.
627
+ * @param params Extension paramters defined in the AgentCard's extensions.
628
+ * @returns A Promise that resolves to the RPC response.
629
+ */
630
+ async callExtensionMethod(method, params) {
631
+ const transport = await this._getOrCreateTransport();
632
+ try {
633
+ return await transport.callExtensionMethod(
634
+ method,
635
+ params,
636
+ this.requestIdCounter++
637
+ );
638
+ } catch (e) {
639
+ const errorResponse = extractJSONRPCError(e);
640
+ if (errorResponse) {
641
+ return errorResponse;
642
+ }
643
+ throw e;
644
+ }
645
+ }
646
+ /**
647
+ * Resubscribes to a task's event stream using Server-Sent Events (SSE).
648
+ * This is used if a previous SSE connection for an active task was broken.
649
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
650
+ * @param params Parameters containing the taskId.
651
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
652
+ */
653
+ async *resubscribeTask(params) {
654
+ const agentCard = await this.agentCardPromise;
655
+ if (!agentCard.capabilities?.streaming) {
656
+ throw new Error("Agent does not support streaming (required for tasks/resubscribe).");
657
+ }
658
+ const transport = await this._getOrCreateTransport();
659
+ yield* transport.resubscribeTask(params);
660
+ }
661
+ ////////////////////////////////////////////////////////////////////////////////
662
+ // Functions used to support old A2AClient Constructor to be deprecated soon
663
+ // TODOs:
664
+ // * remove `agentCardPromise`, and just use agentCard initialized
665
+ // * _getServiceEndpoint can be made synchronous or deleted and accessed via
666
+ // agentCard.url
667
+ // * getAgentCard changed to this.agentCard
668
+ // * delete resolveAgentCardUrl(), _fetchAndCacheAgentCard(),
669
+ // agentCardPath from A2AClientOptions
670
+ // * delete _getOrCreateTransport
671
+ ////////////////////////////////////////////////////////////////////////////////
672
+ async _getOrCreateTransport() {
673
+ if (this.transport) {
674
+ return this.transport;
675
+ }
676
+ const endpoint = await this._getServiceEndpoint();
677
+ this.transport = new JsonRpcTransport({ fetchImpl: this.customFetchImpl, endpoint });
678
+ return this.transport;
679
+ }
680
+ /**
681
+ * Fetches the Agent Card from the agent's well-known URI and caches its service endpoint URL.
682
+ * This method is called by the constructor.
683
+ * @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com)
684
+ * @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
685
+ * @returns A Promise that resolves to the AgentCard.
686
+ */
687
+ async _fetchAndCacheAgentCard(agentBaseUrl, agentCardPath) {
688
+ try {
689
+ const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
690
+ const response = await this._fetch(agentCardUrl, {
691
+ headers: { Accept: "application/json" }
692
+ });
693
+ if (!response.ok) {
694
+ throw new Error(
695
+ `Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
696
+ );
697
+ }
698
+ const agentCard = await response.json();
699
+ if (!agentCard.url) {
700
+ throw new Error(
701
+ "Fetched Agent Card does not contain a valid 'url' for the service endpoint."
702
+ );
703
+ }
704
+ this.serviceEndpointUrl = agentCard.url;
705
+ return agentCard;
706
+ } catch (error) {
707
+ console.error("Error fetching or parsing Agent Card:", error);
708
+ throw error;
709
+ }
710
+ }
711
+ /**
712
+ * Retrieves the Agent Card.
713
+ * If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
714
+ * Otherwise, it returns the card fetched and cached during client construction.
715
+ * @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
716
+ * @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
717
+ * If provided, this will fetch a new card, not use the cached one from the constructor's URL.
718
+ * @returns A Promise that resolves to the AgentCard.
719
+ */
720
+ async getAgentCard(agentBaseUrl, agentCardPath) {
721
+ if (agentBaseUrl) {
722
+ const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
723
+ const response = await this._fetch(agentCardUrl, {
724
+ headers: { Accept: "application/json" }
725
+ });
726
+ if (!response.ok) {
727
+ throw new Error(
728
+ `Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
729
+ );
730
+ }
731
+ return await response.json();
732
+ }
733
+ return this.agentCardPromise;
734
+ }
735
+ /**
736
+ * Determines the agent card URL based on the agent URL.
737
+ * @param agentBaseUrl The agent URL.
738
+ * @param agentCardPath Optional relative path to the agent card, defaults to .well-known/agent-card.json
739
+ */
740
+ resolveAgentCardUrl(agentBaseUrl, agentCardPath = AGENT_CARD_PATH) {
741
+ return `${agentBaseUrl.replace(/\/$/, "")}/${agentCardPath.replace(/^\//, "")}`;
742
+ }
743
+ /**
744
+ * Gets the RPC service endpoint URL. Ensures the agent card has been fetched first.
745
+ * @returns A Promise that resolves to the service endpoint URL string.
746
+ */
747
+ async _getServiceEndpoint() {
748
+ if (this.serviceEndpointUrl) {
749
+ return this.serviceEndpointUrl;
750
+ }
751
+ await this.agentCardPromise;
752
+ if (!this.serviceEndpointUrl) {
753
+ throw new Error(
754
+ "Agent Card URL for RPC endpoint is not available. Fetching might have failed."
755
+ );
756
+ }
757
+ return this.serviceEndpointUrl;
758
+ }
759
+ async invokeJsonRpc(caller, params) {
760
+ const transport = await this._getOrCreateTransport();
761
+ const requestId = this.requestIdCounter++;
762
+ try {
763
+ const result = await caller(transport, params, requestId);
764
+ return {
765
+ id: requestId,
766
+ jsonrpc: "2.0",
767
+ result: result ?? null
768
+ // JSON-RPC requires result property on success, it will be null for "void" methods.
769
+ };
770
+ } catch (e) {
771
+ const errorResponse = extractJSONRPCError(e);
772
+ if (errorResponse) {
773
+ return errorResponse;
774
+ }
775
+ throw e;
776
+ }
777
+ }
778
+ };
779
+ function extractJSONRPCError(error) {
780
+ if (error instanceof Object && "errorResponse" in error && error.errorResponse instanceof Object && "jsonrpc" in error.errorResponse && error.errorResponse.jsonrpc === "2.0" && "error" in error.errorResponse && error.errorResponse.error !== null) {
781
+ return error.errorResponse;
782
+ } else {
783
+ return void 0;
784
+ }
785
+ }
786
+
787
+ // src/client/auth-handler.ts
788
+ function createAuthenticatingFetchWithRetry(fetchImpl, authHandler) {
789
+ async function authFetch(url, init) {
790
+ const authHeaders = await authHandler.headers() || {};
791
+ const mergedInit = {
792
+ ...init || {},
793
+ headers: {
794
+ ...authHeaders,
795
+ ...init?.headers || {}
796
+ }
797
+ };
798
+ let response = await fetchImpl(url, mergedInit);
799
+ const updatedHeaders = await authHandler.shouldRetryWithHeaders(mergedInit, response);
800
+ if (updatedHeaders) {
801
+ const retryInit = {
802
+ ...init || {},
803
+ headers: {
804
+ ...updatedHeaders,
805
+ ...init?.headers || {}
806
+ }
807
+ };
808
+ response = await fetchImpl(url, retryInit);
809
+ if (response.ok && authHandler.onSuccessfulRetry) {
810
+ await authHandler.onSuccessfulRetry(updatedHeaders);
811
+ }
812
+ }
813
+ return response;
814
+ }
815
+ Object.setPrototypeOf(authFetch, Object.getPrototypeOf(fetchImpl));
816
+ Object.defineProperties(authFetch, Object.getOwnPropertyDescriptors(fetchImpl));
817
+ return authFetch;
818
+ }
819
+
820
+ // src/client/card-resolver.ts
821
+ var DefaultAgentCardResolver = class {
822
+ constructor(options) {
823
+ this.options = options;
824
+ }
825
+ /**
826
+ * Fetches the agent card based on provided base URL and path.
827
+ * Path is selected in the following order:
828
+ * 1) path parameter
829
+ * 2) path from options
830
+ * 3) .well-known/agent-card.json
831
+ */
832
+ async resolve(baseUrl, path) {
833
+ const agentCardUrl = new URL(path ?? this.options?.path ?? AGENT_CARD_PATH, baseUrl);
834
+ const response = await this.fetchImpl(agentCardUrl);
835
+ if (!response.ok) {
836
+ throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status}`);
837
+ }
838
+ return await response.json();
839
+ }
840
+ fetchImpl(...args) {
841
+ if (this.options?.fetchImpl) {
842
+ return this.options.fetchImpl(...args);
843
+ }
844
+ return fetch(...args);
845
+ }
846
+ };
847
+ var AgentCardResolver = {
848
+ default: new DefaultAgentCardResolver()
849
+ };
850
+
851
+ // src/client/multitransport-client.ts
852
+ var Client = class {
853
+ constructor(transport, agentCard, config) {
854
+ this.transport = transport;
855
+ this.agentCard = agentCard;
856
+ this.config = config;
857
+ }
858
+ /**
859
+ * If the current agent card supports the extended feature, it will try to fetch the extended agent card from the server,
860
+ * Otherwise it will return the current agent card value.
861
+ */
862
+ async getAgentCard(options) {
863
+ if (this.agentCard.supportsAuthenticatedExtendedCard) {
864
+ this.agentCard = await this.executeWithInterceptors(
865
+ { method: "getAgentCard" },
866
+ options,
867
+ (_, options2) => this.transport.getExtendedAgentCard(options2)
868
+ );
869
+ }
870
+ return this.agentCard;
871
+ }
872
+ /**
873
+ * Sends a message to an agent to initiate a new interaction or to continue an existing one.
874
+ * Uses blocking mode by default.
875
+ */
876
+ sendMessage(params, options) {
877
+ params = this.applyClientConfig({
878
+ params,
879
+ blocking: !(this.config?.polling ?? false)
880
+ });
881
+ return this.executeWithInterceptors(
882
+ { method: "sendMessage", value: params },
883
+ options,
884
+ this.transport.sendMessage.bind(this.transport)
885
+ );
886
+ }
887
+ /**
888
+ * Sends a message to an agent to initiate/continue a task AND subscribes the client to real-time updates for that task.
889
+ * Performs fallback to non-streaming if not supported by the agent.
890
+ */
891
+ async *sendMessageStream(params, options) {
892
+ const method = "sendMessageStream";
893
+ params = this.applyClientConfig({ params, blocking: true });
894
+ const beforeArgs = {
895
+ input: { method, value: params },
896
+ agentCard: this.agentCard,
897
+ options
898
+ };
899
+ const beforeResult = await this.interceptBefore(beforeArgs);
900
+ if (beforeResult) {
901
+ const earlyReturn = beforeResult.earlyReturn.value;
902
+ const afterArgs = {
903
+ result: { method, value: earlyReturn },
904
+ agentCard: this.agentCard,
905
+ options: beforeArgs.options
906
+ };
907
+ await this.interceptAfter(afterArgs, beforeResult.executed);
908
+ yield afterArgs.result.value;
909
+ return;
910
+ }
911
+ if (!this.agentCard.capabilities.streaming) {
912
+ const result = await this.transport.sendMessage(beforeArgs.input.value, beforeArgs.options);
913
+ const afterArgs = {
914
+ result: { method, value: result },
915
+ agentCard: this.agentCard,
916
+ options: beforeArgs.options
917
+ };
918
+ await this.interceptAfter(afterArgs);
919
+ yield afterArgs.result.value;
920
+ return;
921
+ }
922
+ for await (const event of this.transport.sendMessageStream(
923
+ beforeArgs.input.value,
924
+ beforeArgs.options
925
+ )) {
926
+ const afterArgs = {
927
+ result: { method, value: event },
928
+ agentCard: this.agentCard,
929
+ options: beforeArgs.options
930
+ };
931
+ await this.interceptAfter(afterArgs);
932
+ yield afterArgs.result.value;
933
+ if (afterArgs.earlyReturn) {
934
+ return;
935
+ }
936
+ }
937
+ }
938
+ /**
939
+ * Sets or updates the push notification configuration for a specified task.
940
+ * Requires the server to have AgentCard.capabilities.pushNotifications: true.
941
+ */
942
+ setTaskPushNotificationConfig(params, options) {
943
+ if (!this.agentCard.capabilities.pushNotifications) {
944
+ throw new PushNotificationNotSupportedError();
945
+ }
946
+ return this.executeWithInterceptors(
947
+ { method: "setTaskPushNotificationConfig", value: params },
948
+ options,
949
+ this.transport.setTaskPushNotificationConfig.bind(this.transport)
950
+ );
951
+ }
952
+ /**
953
+ * Retrieves the current push notification configuration for a specified task.
954
+ * Requires the server to have AgentCard.capabilities.pushNotifications: true.
955
+ */
956
+ getTaskPushNotificationConfig(params, options) {
957
+ if (!this.agentCard.capabilities.pushNotifications) {
958
+ throw new PushNotificationNotSupportedError();
959
+ }
960
+ return this.executeWithInterceptors(
961
+ { method: "getTaskPushNotificationConfig", value: params },
962
+ options,
963
+ this.transport.getTaskPushNotificationConfig.bind(this.transport)
964
+ );
965
+ }
966
+ /**
967
+ * Retrieves the associated push notification configurations for a specified task.
968
+ * Requires the server to have AgentCard.capabilities.pushNotifications: true.
969
+ */
970
+ listTaskPushNotificationConfig(params, options) {
971
+ if (!this.agentCard.capabilities.pushNotifications) {
972
+ throw new PushNotificationNotSupportedError();
973
+ }
974
+ return this.executeWithInterceptors(
975
+ { method: "listTaskPushNotificationConfig", value: params },
976
+ options,
977
+ this.transport.listTaskPushNotificationConfig.bind(this.transport)
978
+ );
979
+ }
980
+ /**
981
+ * Deletes an associated push notification configuration for a task.
982
+ */
983
+ deleteTaskPushNotificationConfig(params, options) {
984
+ return this.executeWithInterceptors(
985
+ { method: "deleteTaskPushNotificationConfig", value: params },
986
+ options,
987
+ this.transport.deleteTaskPushNotificationConfig.bind(this.transport)
988
+ );
989
+ }
990
+ /**
991
+ * Retrieves the current state (including status, artifacts, and optionally history) of a previously initiated task.
992
+ */
993
+ getTask(params, options) {
994
+ return this.executeWithInterceptors(
995
+ { method: "getTask", value: params },
996
+ options,
997
+ this.transport.getTask.bind(this.transport)
998
+ );
999
+ }
1000
+ /**
1001
+ * Requests the cancellation of an ongoing task. The server will attempt to cancel the task,
1002
+ * but success is not guaranteed (e.g., the task might have already completed or failed, or cancellation might not be supported at its current stage).
1003
+ */
1004
+ cancelTask(params, options) {
1005
+ return this.executeWithInterceptors(
1006
+ { method: "cancelTask", value: params },
1007
+ options,
1008
+ this.transport.cancelTask.bind(this.transport)
1009
+ );
1010
+ }
1011
+ /**
1012
+ * Allows a client to reconnect to an updates stream for an ongoing task after a previous connection was interrupted.
1013
+ */
1014
+ async *resubscribeTask(params, options) {
1015
+ const method = "resubscribeTask";
1016
+ const beforeArgs = {
1017
+ input: { method, value: params },
1018
+ agentCard: this.agentCard,
1019
+ options
1020
+ };
1021
+ const beforeResult = await this.interceptBefore(beforeArgs);
1022
+ if (beforeResult) {
1023
+ const earlyReturn = beforeResult.earlyReturn.value;
1024
+ const afterArgs = {
1025
+ result: { method, value: earlyReturn },
1026
+ agentCard: this.agentCard,
1027
+ options: beforeArgs.options
1028
+ };
1029
+ await this.interceptAfter(afterArgs, beforeResult.executed);
1030
+ yield afterArgs.result.value;
1031
+ return;
1032
+ }
1033
+ for await (const event of this.transport.resubscribeTask(
1034
+ beforeArgs.input.value,
1035
+ beforeArgs.options
1036
+ )) {
1037
+ const afterArgs = {
1038
+ result: { method, value: event },
1039
+ agentCard: this.agentCard,
1040
+ options: beforeArgs.options
1041
+ };
1042
+ await this.interceptAfter(afterArgs);
1043
+ yield afterArgs.result.value;
1044
+ if (afterArgs.earlyReturn) {
1045
+ return;
1046
+ }
1047
+ }
1048
+ }
1049
+ applyClientConfig({
1050
+ params,
1051
+ blocking
1052
+ }) {
1053
+ const result = { ...params, configuration: params.configuration ?? {} };
1054
+ if (!result.configuration.acceptedOutputModes && this.config?.acceptedOutputModes) {
1055
+ result.configuration.acceptedOutputModes = this.config.acceptedOutputModes;
1056
+ }
1057
+ if (!result.configuration.pushNotificationConfig && this.config?.pushNotificationConfig) {
1058
+ result.configuration.pushNotificationConfig = this.config.pushNotificationConfig;
1059
+ }
1060
+ result.configuration.blocking ??= blocking;
1061
+ return result;
1062
+ }
1063
+ async executeWithInterceptors(input, options, transportCall) {
1064
+ const beforeArgs = {
1065
+ input,
1066
+ agentCard: this.agentCard,
1067
+ options
1068
+ };
1069
+ const beforeResult = await this.interceptBefore(beforeArgs);
1070
+ if (beforeResult) {
1071
+ const afterArgs2 = {
1072
+ result: {
1073
+ method: input.method,
1074
+ value: beforeResult.earlyReturn.value
1075
+ },
1076
+ agentCard: this.agentCard,
1077
+ options: beforeArgs.options
1078
+ };
1079
+ await this.interceptAfter(afterArgs2, beforeResult.executed);
1080
+ return afterArgs2.result.value;
1081
+ }
1082
+ const result = await transportCall(beforeArgs.input.value, beforeArgs.options);
1083
+ const afterArgs = {
1084
+ result: { method: input.method, value: result },
1085
+ agentCard: this.agentCard,
1086
+ options: beforeArgs.options
1087
+ };
1088
+ await this.interceptAfter(afterArgs);
1089
+ return afterArgs.result.value;
1090
+ }
1091
+ async interceptBefore(args) {
1092
+ if (!this.config?.interceptors || this.config.interceptors.length === 0) {
1093
+ return;
1094
+ }
1095
+ const executed = [];
1096
+ for (const interceptor of this.config.interceptors) {
1097
+ await interceptor.before(args);
1098
+ executed.push(interceptor);
1099
+ if (args.earlyReturn) {
1100
+ return {
1101
+ earlyReturn: args.earlyReturn,
1102
+ executed
1103
+ };
1104
+ }
1105
+ }
1106
+ }
1107
+ async interceptAfter(args, interceptors) {
1108
+ const reversedInterceptors = [...interceptors ?? this.config?.interceptors ?? []].reverse();
1109
+ for (const interceptor of reversedInterceptors) {
1110
+ await interceptor.after(args);
1111
+ if (args.earlyReturn) {
1112
+ return;
1113
+ }
1114
+ }
1115
+ }
1116
+ };
1117
+
1118
+ // src/client/transports/rest_transport.ts
1119
+ var RestTransport = class _RestTransport {
1120
+ customFetchImpl;
1121
+ endpoint;
1122
+ constructor(options) {
1123
+ this.endpoint = options.endpoint.replace(/\/+$/, "");
1124
+ this.customFetchImpl = options.fetchImpl;
1125
+ }
1126
+ async getExtendedAgentCard(options) {
1127
+ return this._sendRequest("GET", "/v1/card", void 0, options);
1128
+ }
1129
+ async sendMessage(params, options) {
1130
+ return this._sendRequest("POST", "/v1/message:send", params, options);
1131
+ }
1132
+ async *sendMessageStream(params, options) {
1133
+ yield* this._sendStreamingRequest("/v1/message:stream", params, options);
1134
+ }
1135
+ async setTaskPushNotificationConfig(params, options) {
1136
+ return this._sendRequest(
1137
+ "POST",
1138
+ `/v1/tasks/${encodeURIComponent(params.taskId)}/pushNotificationConfigs`,
1139
+ {
1140
+ pushNotificationConfig: params.pushNotificationConfig
1141
+ },
1142
+ options
1143
+ );
1144
+ }
1145
+ async getTaskPushNotificationConfig(params, options) {
1146
+ const { pushNotificationConfigId } = params;
1147
+ if (!pushNotificationConfigId) {
1148
+ throw new Error(
1149
+ "pushNotificationConfigId is required for getTaskPushNotificationConfig with REST transport."
1150
+ );
1151
+ }
1152
+ return this._sendRequest(
1153
+ "GET",
1154
+ `/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs/${encodeURIComponent(pushNotificationConfigId)}`,
1155
+ void 0,
1156
+ options
1157
+ );
1158
+ }
1159
+ async listTaskPushNotificationConfig(params, options) {
1160
+ return this._sendRequest(
1161
+ "GET",
1162
+ `/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs`,
1163
+ void 0,
1164
+ options
1165
+ );
1166
+ }
1167
+ async deleteTaskPushNotificationConfig(params, options) {
1168
+ await this._sendRequest(
1169
+ "DELETE",
1170
+ `/v1/tasks/${encodeURIComponent(params.id)}/pushNotificationConfigs/${encodeURIComponent(params.pushNotificationConfigId)}`,
1171
+ void 0,
1172
+ options
1173
+ );
1174
+ }
1175
+ async getTask(params, options) {
1176
+ const queryParams = new URLSearchParams();
1177
+ if (params.historyLength !== void 0) {
1178
+ queryParams.set("historyLength", String(params.historyLength));
1179
+ }
1180
+ const queryString = queryParams.toString();
1181
+ const path = `/v1/tasks/${encodeURIComponent(params.id)}${queryString ? `?${queryString}` : ""}`;
1182
+ return this._sendRequest("GET", path, void 0, options);
1183
+ }
1184
+ async cancelTask(params, options) {
1185
+ return this._sendRequest(
1186
+ "POST",
1187
+ `/v1/tasks/${encodeURIComponent(params.id)}:cancel`,
1188
+ void 0,
1189
+ options
1190
+ );
1191
+ }
1192
+ async *resubscribeTask(params, options) {
1193
+ yield* this._sendStreamingRequest(
1194
+ `/v1/tasks/${encodeURIComponent(params.id)}:subscribe`,
1195
+ void 0,
1196
+ options
1197
+ );
1198
+ }
1199
+ _fetch(...args) {
1200
+ if (this.customFetchImpl) {
1201
+ return this.customFetchImpl(...args);
1202
+ }
1203
+ if (typeof fetch === "function") {
1204
+ return fetch(...args);
1205
+ }
1206
+ throw new Error(
1207
+ "A `fetch` implementation was not provided and is not available in the global scope. Please provide a `fetchImpl` in the RestTransportOptions."
1208
+ );
1209
+ }
1210
+ _buildHeaders(options, acceptHeader = "application/json") {
1211
+ return {
1212
+ ...options?.serviceParameters,
1213
+ "Content-Type": "application/json",
1214
+ Accept: acceptHeader
1215
+ };
1216
+ }
1217
+ async _sendRequest(method, path, body, options) {
1218
+ const url = `${this.endpoint}${path}`;
1219
+ const requestInit = {
1220
+ method,
1221
+ headers: this._buildHeaders(options),
1222
+ signal: options?.signal
1223
+ };
1224
+ if (body !== void 0 && method !== "GET") {
1225
+ requestInit.body = JSON.stringify(body);
1226
+ }
1227
+ const response = await this._fetch(url, requestInit);
1228
+ if (!response.ok) {
1229
+ await this._handleErrorResponse(response, path);
1230
+ }
1231
+ if (response.status === 204) {
1232
+ return void 0;
1233
+ }
1234
+ const result = await response.json();
1235
+ return result;
1236
+ }
1237
+ async _handleErrorResponse(response, path) {
1238
+ let errorBodyText = "(empty or non-JSON response)";
1239
+ let errorBody;
1240
+ try {
1241
+ errorBodyText = await response.text();
1242
+ if (errorBodyText) {
1243
+ errorBody = JSON.parse(errorBodyText);
1244
+ }
1245
+ } catch (e) {
1246
+ throw new Error(
1247
+ `HTTP error for ${path}! Status: ${response.status} ${response.statusText}. Response: ${errorBodyText}`,
1248
+ { cause: e }
1249
+ );
1250
+ }
1251
+ if (errorBody && typeof errorBody.code === "number") {
1252
+ throw _RestTransport.mapToError(errorBody);
1253
+ }
1254
+ throw new Error(
1255
+ `HTTP error for ${path}! Status: ${response.status} ${response.statusText}. Response: ${errorBodyText}`
1256
+ );
1257
+ }
1258
+ async *_sendStreamingRequest(path, body, options) {
1259
+ const url = `${this.endpoint}${path}`;
1260
+ const requestInit = {
1261
+ method: "POST",
1262
+ headers: this._buildHeaders(options, "text/event-stream"),
1263
+ signal: options?.signal
1264
+ };
1265
+ if (body !== void 0) {
1266
+ requestInit.body = JSON.stringify(body);
1267
+ }
1268
+ const response = await this._fetch(url, requestInit);
1269
+ if (!response.ok) {
1270
+ await this._handleErrorResponse(response, path);
1271
+ }
1272
+ const contentType = response.headers.get("Content-Type");
1273
+ if (!contentType?.startsWith("text/event-stream")) {
1274
+ throw new Error(
1275
+ `Invalid response Content-Type for SSE stream. Expected 'text/event-stream', got '${contentType}'.`
1276
+ );
1277
+ }
1278
+ for await (const event of parseSseStream(response)) {
1279
+ if (event.type === "error") {
1280
+ const errorData = JSON.parse(event.data);
1281
+ throw _RestTransport.mapToError(errorData);
1282
+ }
1283
+ yield this._processSseEventData(event.data);
1284
+ }
1285
+ }
1286
+ _processSseEventData(jsonData) {
1287
+ if (!jsonData.trim()) {
1288
+ throw new Error("Attempted to process empty SSE event data.");
1289
+ }
1290
+ try {
1291
+ const data = JSON.parse(jsonData);
1292
+ return data;
1293
+ } catch (e) {
1294
+ console.error("Failed to parse SSE event data:", jsonData, e);
1295
+ throw new Error(
1296
+ `Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${e instanceof Error && e.message || "Unknown error"}`
1297
+ );
1298
+ }
1299
+ }
1300
+ static mapToError(error) {
1301
+ switch (error.code) {
1302
+ case A2A_ERROR_CODE.TASK_NOT_FOUND:
1303
+ return new TaskNotFoundError(error.message);
1304
+ case A2A_ERROR_CODE.TASK_NOT_CANCELABLE:
1305
+ return new TaskNotCancelableError(error.message);
1306
+ case A2A_ERROR_CODE.PUSH_NOTIFICATION_NOT_SUPPORTED:
1307
+ return new PushNotificationNotSupportedError(error.message);
1308
+ case A2A_ERROR_CODE.UNSUPPORTED_OPERATION:
1309
+ return new UnsupportedOperationError(error.message);
1310
+ case A2A_ERROR_CODE.CONTENT_TYPE_NOT_SUPPORTED:
1311
+ return new ContentTypeNotSupportedError(error.message);
1312
+ case A2A_ERROR_CODE.INVALID_AGENT_RESPONSE:
1313
+ return new InvalidAgentResponseError(error.message);
1314
+ case A2A_ERROR_CODE.AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED:
1315
+ return new AuthenticatedExtendedCardNotConfiguredError(error.message);
1316
+ default:
1317
+ return new Error(
1318
+ `REST error: ${error.message} (Code: ${error.code})${error.data ? ` Data: ${JSON.stringify(error.data)}` : ""}`
1319
+ );
1320
+ }
1321
+ }
1322
+ };
1323
+ var RestTransportFactory = class _RestTransportFactory {
1324
+ constructor(options) {
1325
+ this.options = options;
1326
+ }
1327
+ static name = "HTTP+JSON";
1328
+ get protocolName() {
1329
+ return _RestTransportFactory.name;
1330
+ }
1331
+ async create(url, _agentCard) {
1332
+ return new RestTransport({
1333
+ endpoint: url,
1334
+ fetchImpl: this.options?.fetchImpl
1335
+ });
1336
+ }
1337
+ };
1338
+
1339
+ // src/client/factory.ts
1340
+ var ClientFactoryOptions = {
1341
+ /**
1342
+ * SDK default options for {@link ClientFactory}.
1343
+ */
1344
+ default: {
1345
+ transports: [new JsonRpcTransportFactory(), new RestTransportFactory()]
1346
+ },
1347
+ /**
1348
+ * Creates new options by merging an original and an override object.
1349
+ * Transports are merged based on `TransportFactory.protocolName`,
1350
+ * interceptors are concatenated, other fields are overriden.
1351
+ *
1352
+ * @example
1353
+ * ```ts
1354
+ * const options = ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
1355
+ * transports: [new MyCustomTransportFactory()], // adds a custom transport
1356
+ * clientConfig: { interceptors: [new MyInterceptor()] }, // adds a custom interceptor
1357
+ * });
1358
+ * ```
1359
+ */
1360
+ createFrom(original, overrides) {
1361
+ return {
1362
+ ...original,
1363
+ ...overrides,
1364
+ transports: mergeTransports(original.transports, overrides.transports),
1365
+ clientConfig: {
1366
+ ...original.clientConfig ?? {},
1367
+ ...overrides.clientConfig ?? {},
1368
+ interceptors: mergeArrays(
1369
+ original.clientConfig?.interceptors,
1370
+ overrides.clientConfig?.interceptors
1371
+ ),
1372
+ acceptedOutputModes: overrides.clientConfig?.acceptedOutputModes ?? original.clientConfig?.acceptedOutputModes
1373
+ },
1374
+ preferredTransports: overrides.preferredTransports ?? original.preferredTransports
1375
+ };
1376
+ }
1377
+ };
1378
+ var ClientFactory = class {
1379
+ constructor(options = ClientFactoryOptions.default) {
1380
+ this.options = options;
1381
+ if (!options.transports || options.transports.length === 0) {
1382
+ throw new Error("No transports provided");
1383
+ }
1384
+ this.transportsByName = transportsByName(options.transports);
1385
+ for (const transport of options.preferredTransports ?? []) {
1386
+ if (!this.transportsByName.has(transport)) {
1387
+ throw new Error(
1388
+ `Unknown preferred transport: ${transport}, available transports: ${[...this.transportsByName.keys()].join()}`
1389
+ );
1390
+ }
1391
+ }
1392
+ this.agentCardResolver = options.cardResolver ?? AgentCardResolver.default;
1393
+ }
1394
+ transportsByName;
1395
+ agentCardResolver;
1396
+ /**
1397
+ * Creates a new client from the provided agent card.
1398
+ */
1399
+ async createFromAgentCard(agentCard) {
1400
+ const agentCardPreferred = agentCard.preferredTransport ?? JsonRpcTransportFactory.name;
1401
+ const additionalInterfaces = agentCard.additionalInterfaces ?? [];
1402
+ const urlsPerAgentTransports = new CaseInsensitiveMap([
1403
+ [agentCardPreferred, agentCard.url],
1404
+ ...additionalInterfaces.map((i) => [i.transport, i.url])
1405
+ ]);
1406
+ const transportsByPreference = [
1407
+ ...this.options.preferredTransports ?? [],
1408
+ agentCardPreferred,
1409
+ ...additionalInterfaces.map((i) => i.transport)
1410
+ ];
1411
+ for (const transport of transportsByPreference) {
1412
+ if (!urlsPerAgentTransports.has(transport)) {
1413
+ continue;
1414
+ }
1415
+ const factory = this.transportsByName.get(transport);
1416
+ if (!factory) {
1417
+ continue;
1418
+ }
1419
+ return new Client(
1420
+ await factory.create(urlsPerAgentTransports.get(transport), agentCard),
1421
+ agentCard,
1422
+ this.options.clientConfig
1423
+ );
1424
+ }
1425
+ throw new Error(
1426
+ "No compatible transport found, available transports: " + [...this.transportsByName.keys()].join()
1427
+ );
1428
+ }
1429
+ /**
1430
+ * Downloads agent card using AgentCardResolver from options
1431
+ * and creates a new client from the downloaded card.
1432
+ *
1433
+ * @example
1434
+ * ```ts
1435
+ * const factory = new ClientFactory(); // use default options and default {@link AgentCardResolver}.
1436
+ * const client1 = await factory.createFromUrl('https://example.com'); // /.well-known/agent-card.json is used by default
1437
+ * const client2 = await factory.createFromUrl('https://example.com', '/my-agent-card.json'); // specify custom path
1438
+ * const client3 = await factory.createFromUrl('https://example.com/my-agent-card.json', ''); // specify full URL and set path to empty
1439
+ * ```
1440
+ */
1441
+ async createFromUrl(baseUrl, path) {
1442
+ const agentCard = await this.agentCardResolver.resolve(baseUrl, path);
1443
+ return this.createFromAgentCard(agentCard);
1444
+ }
1445
+ };
1446
+ function mergeTransports(original, overrides) {
1447
+ if (!overrides) {
1448
+ return original;
1449
+ }
1450
+ const result = transportsByName(original);
1451
+ const overridesByName = transportsByName(overrides);
1452
+ for (const [name, factory] of overridesByName) {
1453
+ result.set(name, factory);
1454
+ }
1455
+ return Array.from(result.values());
1456
+ }
1457
+ function transportsByName(transports) {
1458
+ const result = new CaseInsensitiveMap();
1459
+ if (!transports) {
1460
+ return result;
1461
+ }
1462
+ for (const t of transports) {
1463
+ if (result.has(t.protocolName)) {
1464
+ throw new Error(`Duplicate protocol name: ${t.protocolName}`);
1465
+ }
1466
+ result.set(t.protocolName, t);
1467
+ }
1468
+ return result;
1469
+ }
1470
+ function mergeArrays(a1, a2) {
1471
+ if (!a1 && !a2) {
1472
+ return void 0;
1473
+ }
1474
+ return [...a1 ?? [], ...a2 ?? []];
1475
+ }
1476
+ var CaseInsensitiveMap = class extends Map {
1477
+ normalizeKey(key) {
1478
+ return key.toUpperCase();
1479
+ }
1480
+ set(key, value) {
1481
+ return super.set(this.normalizeKey(key), value);
1482
+ }
1483
+ get(key) {
1484
+ return super.get(this.normalizeKey(key));
1485
+ }
1486
+ has(key) {
1487
+ return super.has(this.normalizeKey(key));
1488
+ }
1489
+ delete(key) {
1490
+ return super.delete(this.normalizeKey(key));
1491
+ }
1492
+ };
1493
+
1494
+ // src/extensions.ts
1495
+ var Extensions = {
1496
+ /**
1497
+ * Creates new {@link Extensions} from `current` and `additional`.
1498
+ * If `current` already contains `additional` it is returned unmodified.
1499
+ */
1500
+ createFrom: (current, additional) => {
1501
+ if (current?.includes(additional)) {
1502
+ return current;
1503
+ }
1504
+ return [...current ?? [], additional];
1505
+ },
1506
+ /**
1507
+ * Creates {@link Extensions} from comma separated extensions identifiers as per
1508
+ * https://a2a-protocol.org/latest/specification/#326-service-parameters.
1509
+ * Parses the output of `toServiceParameter`.
1510
+ */
1511
+ parseServiceParameter: (value) => {
1512
+ if (!value) {
1513
+ return [];
1514
+ }
1515
+ const unique = new Set(
1516
+ value.split(",").map((ext) => ext.trim()).filter((ext) => ext.length > 0)
1517
+ );
1518
+ return Array.from(unique);
1519
+ },
1520
+ /**
1521
+ * Converts {@link Extensions} to comma separated extensions identifiers as per
1522
+ * https://a2a-protocol.org/latest/specification/#326-service-parameters.
1523
+ */
1524
+ toServiceParameter: (value) => {
1525
+ return value.join(",");
1526
+ }
1527
+ };
1528
+
1529
+ // src/client/service-parameters.ts
1530
+ var ServiceParameters = {
1531
+ create(...updates) {
1532
+ return ServiceParameters.createFrom(void 0, ...updates);
1533
+ },
1534
+ createFrom: (serviceParameters, ...updates) => {
1535
+ const result = serviceParameters ? { ...serviceParameters } : {};
1536
+ for (const update of updates) {
1537
+ update(result);
1538
+ }
1539
+ return result;
1540
+ }
1541
+ };
1542
+ function withA2AExtensions(...extensions) {
1543
+ return (parameters) => {
1544
+ parameters[HTTP_EXTENSION_HEADER] = Extensions.toServiceParameter(extensions);
1545
+ };
1546
+ }
1547
+
1548
+ // src/client/context.ts
1549
+ var ClientCallContext = {
1550
+ /**
1551
+ * Create a new {@link ClientCallContext} with optional updates applied.
1552
+ */
1553
+ create: (...updates) => {
1554
+ return ClientCallContext.createFrom(void 0, ...updates);
1555
+ },
1556
+ /**
1557
+ * Create a new {@link ClientCallContext} based on an existing one with updates applied.
1558
+ */
1559
+ createFrom: (context, ...updates) => {
1560
+ const result = context ? { ...context } : {};
1561
+ for (const update of updates) {
1562
+ update(result);
1563
+ }
1564
+ return result;
1565
+ }
1566
+ };
1567
+ var ClientCallContextKey = class {
1568
+ symbol;
1569
+ constructor(description) {
1570
+ this.symbol = Symbol(description);
1571
+ }
1572
+ set(value) {
1573
+ return (context) => {
1574
+ context[this.symbol] = value;
1575
+ };
1576
+ }
1577
+ get(context) {
1578
+ return context[this.symbol];
1579
+ }
1580
+ };
1581
+ // Annotate the CommonJS export names for ESM import in node:
1582
+ 0 && (module.exports = {
1583
+ A2AClient,
1584
+ AgentCardResolver,
1585
+ AuthenticatedExtendedCardNotConfiguredError,
1586
+ Client,
1587
+ ClientCallContext,
1588
+ ClientCallContextKey,
1589
+ ClientFactory,
1590
+ ClientFactoryOptions,
1591
+ ContentTypeNotSupportedError,
1592
+ DefaultAgentCardResolver,
1593
+ InvalidAgentResponseError,
1594
+ JsonRpcTransport,
1595
+ JsonRpcTransportFactory,
1596
+ PushNotificationNotSupportedError,
1597
+ RestTransport,
1598
+ RestTransportFactory,
1599
+ ServiceParameters,
1600
+ TaskNotCancelableError,
1601
+ TaskNotFoundError,
1602
+ UnsupportedOperationError,
1603
+ createAuthenticatingFetchWithRetry,
1604
+ withA2AExtensions
1605
+ });