@a2a-js/sdk 0.3.5 → 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.
@@ -20,20 +20,431 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  var client_exports = {};
21
21
  __export(client_exports, {
22
22
  A2AClient: () => A2AClient,
23
- createAuthenticatingFetchWithRetry: () => createAuthenticatingFetchWithRetry
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
24
44
  });
25
45
  module.exports = __toCommonJS(client_exports);
26
46
 
27
47
  // src/constants.ts
28
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
+ };
29
435
 
30
436
  // src/client/client.ts
31
437
  var A2AClient = class _A2AClient {
438
+ static emptyOptions = void 0;
32
439
  agentCardPromise;
33
- requestIdCounter = 1;
34
- serviceEndpointUrl;
35
- // To be populated from AgentCard after fetching
36
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;
37
448
  /**
38
449
  * Constructs an A2AClient instance from an AgentCard.
39
450
  * @param agentCard The AgentCard object.
@@ -42,18 +453,22 @@ var A2AClient = class _A2AClient {
42
453
  constructor(agentCard, options) {
43
454
  this.customFetchImpl = options?.fetchImpl;
44
455
  if (typeof agentCard === "string") {
45
- console.warn("Warning: Constructing A2AClient with a URL is deprecated. Please use A2AClient.fromCardUrl() instead.");
456
+ console.warn(
457
+ "Warning: Constructing A2AClient with a URL is deprecated. Please use A2AClient.fromCardUrl() instead."
458
+ );
46
459
  this.agentCardPromise = this._fetchAndCacheAgentCard(agentCard, options?.agentCardPath);
47
460
  } else {
48
461
  if (!agentCard.url) {
49
- throw new Error("Provided Agent Card does not contain a valid 'url' for the service endpoint.");
462
+ throw new Error(
463
+ "Provided Agent Card does not contain a valid 'url' for the service endpoint."
464
+ );
50
465
  }
51
466
  this.serviceEndpointUrl = agentCard.url;
52
467
  this.agentCardPromise = Promise.resolve(agentCard);
53
468
  }
54
469
  }
55
470
  /**
56
- * Dynamically resolves the fetch implementation to use for requests.
471
+ * Dynamically resolves the fetch implementation to use for requests.
57
472
  * Prefers a custom implementation if provided, otherwise falls back to the global fetch.
58
473
  * @returns The fetch implementation.
59
474
  * @param args Arguments to pass to the fetch implementation.
@@ -79,7 +494,7 @@ var A2AClient = class _A2AClient {
79
494
  static async fromCardUrl(agentCardUrl, options) {
80
495
  const fetchImpl = options?.fetchImpl;
81
496
  const requestInit = {
82
- headers: { "Accept": "application/json" }
497
+ headers: { Accept: "application/json" }
83
498
  };
84
499
  let response;
85
500
  if (fetchImpl) {
@@ -92,76 +507,21 @@ var A2AClient = class _A2AClient {
92
507
  );
93
508
  }
94
509
  if (!response.ok) {
95
- throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`);
510
+ throw new Error(
511
+ `Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
512
+ );
96
513
  }
97
514
  let agentCard;
98
515
  try {
99
516
  agentCard = await response.json();
100
517
  } catch (error) {
101
518
  console.error("Failed to parse Agent Card JSON:", error);
102
- throw new Error(`Failed to parse Agent Card JSON from ${agentCardUrl}. Original error: ${error.message}`);
519
+ throw new Error(
520
+ `Failed to parse Agent Card JSON from ${agentCardUrl}. Original error: ${error.message}`
521
+ );
103
522
  }
104
523
  return new _A2AClient(agentCard, options);
105
524
  }
106
- /**
107
- * Helper method to make a generic JSON-RPC POST request.
108
- * @param method The RPC method name.
109
- * @param params The parameters for the RPC method.
110
- * @returns A Promise that resolves to the RPC response.
111
- */
112
- async _postRpcRequest(method, params) {
113
- const endpoint = await this._getServiceEndpoint();
114
- const requestId = this.requestIdCounter++;
115
- const rpcRequest = {
116
- jsonrpc: "2.0",
117
- method,
118
- params,
119
- // Cast because TParams structure varies per method
120
- id: requestId
121
- };
122
- const httpResponse = await this._fetchRpc(endpoint, rpcRequest);
123
- if (!httpResponse.ok) {
124
- let errorBodyText = "(empty or non-JSON response)";
125
- try {
126
- errorBodyText = await httpResponse.text();
127
- const errorJson = JSON.parse(errorBodyText);
128
- if (errorJson.jsonrpc && errorJson.error) {
129
- return errorJson;
130
- } else if (!errorJson.jsonrpc && errorJson.error) {
131
- throw new Error(`RPC error for ${method}: ${errorJson.error.message} (Code: ${errorJson.error.code}, HTTP Status: ${httpResponse.status}) Data: ${JSON.stringify(errorJson.error.data || {})}`);
132
- } else if (!errorJson.jsonrpc) {
133
- throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
134
- }
135
- } catch (e) {
136
- if (e.message.startsWith("RPC error for") || e.message.startsWith("HTTP error for")) throw e;
137
- throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
138
- }
139
- }
140
- const rpcResponse = await httpResponse.json();
141
- if (rpcResponse.id !== requestId) {
142
- console.error(`CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}. This may lead to incorrect response handling.`);
143
- }
144
- return rpcResponse;
145
- }
146
- /**
147
- * Internal helper method to fetch the RPC service endpoint.
148
- * @param url The URL to fetch.
149
- * @param rpcRequest The JSON-RPC request to send.
150
- * @param acceptHeader The Accept header to use. Defaults to "application/json".
151
- * @returns A Promise that resolves to the fetch HTTP response.
152
- */
153
- async _fetchRpc(url, rpcRequest, acceptHeader = "application/json") {
154
- const requestInit = {
155
- method: "POST",
156
- headers: {
157
- "Content-Type": "application/json",
158
- "Accept": acceptHeader
159
- // Expect JSON response for non-streaming requests
160
- },
161
- body: JSON.stringify(rpcRequest)
162
- };
163
- return this._fetch(url, requestInit);
164
- }
165
525
  /**
166
526
  * Sends a message to the agent.
167
527
  * The behavior (blocking/non-blocking) and push notification configuration
@@ -171,7 +531,10 @@ var A2AClient = class _A2AClient {
171
531
  * @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
172
532
  */
173
533
  async sendMessage(params) {
174
- return this._postRpcRequest("message/send", params);
534
+ return await this.invokeJsonRpc(
535
+ (t, p, id) => t.sendMessage(p, _A2AClient.emptyOptions, id),
536
+ params
537
+ );
175
538
  }
176
539
  /**
177
540
  * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
@@ -185,36 +548,12 @@ var A2AClient = class _A2AClient {
185
548
  async *sendMessageStream(params) {
186
549
  const agentCard = await this.agentCardPromise;
187
550
  if (!agentCard.capabilities?.streaming) {
188
- throw new Error("Agent does not support streaming (AgentCard.capabilities.streaming is not true).");
189
- }
190
- const endpoint = await this._getServiceEndpoint();
191
- const clientRequestId = this.requestIdCounter++;
192
- const rpcRequest = {
193
- // This is the initial JSON-RPC request to establish the stream
194
- jsonrpc: "2.0",
195
- method: "message/stream",
196
- params,
197
- id: clientRequestId
198
- };
199
- const response = await this._fetchRpc(endpoint, rpcRequest, "text/event-stream");
200
- if (!response.ok) {
201
- let errorBody = "";
202
- try {
203
- errorBody = await response.text();
204
- const errorJson = JSON.parse(errorBody);
205
- if (errorJson.error) {
206
- throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
207
- }
208
- } catch (e) {
209
- if (e.message.startsWith("HTTP error establishing stream")) throw e;
210
- throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. Response: ${errorBody || "(empty)"}`);
211
- }
212
- throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}`);
213
- }
214
- if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
215
- throw new Error("Invalid response Content-Type for SSE stream. Expected 'text/event-stream'.");
551
+ throw new Error(
552
+ "Agent does not support streaming (AgentCard.capabilities.streaming is not true)."
553
+ );
216
554
  }
217
- yield* this._parseA2ASseStream(response, clientRequestId);
555
+ const transport = await this._getOrCreateTransport();
556
+ yield* transport.sendMessageStream(params);
218
557
  }
219
558
  /**
220
559
  * Sets or updates the push notification configuration for a given task.
@@ -225,12 +564,11 @@ var A2AClient = class _A2AClient {
225
564
  async setTaskPushNotificationConfig(params) {
226
565
  const agentCard = await this.agentCardPromise;
227
566
  if (!agentCard.capabilities?.pushNotifications) {
228
- throw new Error("Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true).");
567
+ throw new Error(
568
+ "Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true)."
569
+ );
229
570
  }
230
- return this._postRpcRequest(
231
- "tasks/pushNotificationConfig/set",
232
- params
233
- );
571
+ return await this.invokeJsonRpc((t, p, id) => t.setTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id), params);
234
572
  }
235
573
  /**
236
574
  * Gets the push notification configuration for a given task.
@@ -238,8 +576,8 @@ var A2AClient = class _A2AClient {
238
576
  * @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
239
577
  */
240
578
  async getTaskPushNotificationConfig(params) {
241
- return this._postRpcRequest(
242
- "tasks/pushNotificationConfig/get",
579
+ return await this.invokeJsonRpc(
580
+ (t, p, id) => t.getTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id),
243
581
  params
244
582
  );
245
583
  }
@@ -249,10 +587,7 @@ var A2AClient = class _A2AClient {
249
587
  * @returns A Promise resolving to ListTaskPushNotificationConfigResponse.
250
588
  */
251
589
  async listTaskPushNotificationConfig(params) {
252
- return this._postRpcRequest(
253
- "tasks/pushNotificationConfig/list",
254
- params
255
- );
590
+ return await this.invokeJsonRpc((t, p, id) => t.listTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id), params);
256
591
  }
257
592
  /**
258
593
  * Deletes the push notification configuration for a given task.
@@ -260,10 +595,7 @@ var A2AClient = class _A2AClient {
260
595
  * @returns A Promise resolving to DeleteTaskPushNotificationConfigResponse.
261
596
  */
262
597
  async deleteTaskPushNotificationConfig(params) {
263
- return this._postRpcRequest(
264
- "tasks/pushNotificationConfig/delete",
265
- params
266
- );
598
+ return await this.invokeJsonRpc((t, p, id) => t.deleteTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id), params);
267
599
  }
268
600
  /**
269
601
  * Retrieves a task by its ID.
@@ -271,7 +603,10 @@ var A2AClient = class _A2AClient {
271
603
  * @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
272
604
  */
273
605
  async getTask(params) {
274
- return this._postRpcRequest("tasks/get", params);
606
+ return await this.invokeJsonRpc(
607
+ (t, p, id) => t.getTask(p, _A2AClient.emptyOptions, id),
608
+ params
609
+ );
275
610
  }
276
611
  /**
277
612
  * Cancels a task by its ID.
@@ -279,18 +614,34 @@ var A2AClient = class _A2AClient {
279
614
  * @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
280
615
  */
281
616
  async cancelTask(params) {
282
- return this._postRpcRequest("tasks/cancel", params);
617
+ return await this.invokeJsonRpc(
618
+ (t, p, id) => t.cancelTask(p, _A2AClient.emptyOptions, id),
619
+ params
620
+ );
283
621
  }
284
622
  /**
285
623
  * @template TExtensionParams The type of parameters for the custom extension method.
286
- * @template TExtensionResponse The type of response expected from the custom extension method.
624
+ * @template TExtensionResponse The type of response expected from the custom extension method.
287
625
  * This should extend JSONRPCResponse. This ensures the extension response is still a valid A2A response.
288
626
  * @param method Custom JSON-RPC method defined in the AgentCard's extensions.
289
627
  * @param params Extension paramters defined in the AgentCard's extensions.
290
628
  * @returns A Promise that resolves to the RPC response.
291
629
  */
292
630
  async callExtensionMethod(method, params) {
293
- return this._postRpcRequest(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
+ }
294
645
  }
295
646
  /**
296
647
  * Resubscribes to a task's event stream using Server-Sent Events (SSE).
@@ -304,140 +655,28 @@ var A2AClient = class _A2AClient {
304
655
  if (!agentCard.capabilities?.streaming) {
305
656
  throw new Error("Agent does not support streaming (required for tasks/resubscribe).");
306
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
+ }
307
676
  const endpoint = await this._getServiceEndpoint();
308
- const clientRequestId = this.requestIdCounter++;
309
- const rpcRequest = {
310
- // Initial JSON-RPC request to establish the stream
311
- jsonrpc: "2.0",
312
- method: "tasks/resubscribe",
313
- params,
314
- id: clientRequestId
315
- };
316
- const response = await this._fetch(endpoint, {
317
- method: "POST",
318
- headers: {
319
- "Content-Type": "application/json",
320
- "Accept": "text/event-stream"
321
- },
322
- body: JSON.stringify(rpcRequest)
323
- });
324
- if (!response.ok) {
325
- let errorBody = "";
326
- try {
327
- errorBody = await response.text();
328
- const errorJson = JSON.parse(errorBody);
329
- if (errorJson.error) {
330
- throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
331
- }
332
- } catch (e) {
333
- if (e.message.startsWith("HTTP error establishing stream")) throw e;
334
- throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. Response: ${errorBody || "(empty)"}`);
335
- }
336
- throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}`);
337
- }
338
- if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
339
- throw new Error("Invalid response Content-Type for SSE stream on resubscribe. Expected 'text/event-stream'.");
340
- }
341
- yield* this._parseA2ASseStream(response, clientRequestId);
342
- }
343
- /**
344
- * Parses an HTTP response body as an A2A Server-Sent Event stream.
345
- * Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,
346
- * specifically a SendStreamingMessageResponse (or similar structure for resubscribe).
347
- * @param response The HTTP Response object whose body is the SSE stream.
348
- * @param originalRequestId The ID of the client's JSON-RPC request that initiated this stream.
349
- * Used to validate the `id` in the streamed JSON-RPC responses.
350
- * @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.
351
- */
352
- async *_parseA2ASseStream(response, originalRequestId) {
353
- if (!response.body) {
354
- throw new Error("SSE response body is undefined. Cannot read stream.");
355
- }
356
- const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
357
- let buffer = "";
358
- let eventDataBuffer = "";
359
- try {
360
- while (true) {
361
- const { done, value } = await reader.read();
362
- if (done) {
363
- if (eventDataBuffer.trim()) {
364
- const result = this._processSseEventData(eventDataBuffer, originalRequestId);
365
- yield result;
366
- }
367
- break;
368
- }
369
- buffer += value;
370
- let lineEndIndex;
371
- while ((lineEndIndex = buffer.indexOf("\n")) >= 0) {
372
- const line = buffer.substring(0, lineEndIndex).trim();
373
- buffer = buffer.substring(lineEndIndex + 1);
374
- if (line === "") {
375
- if (eventDataBuffer) {
376
- const result = this._processSseEventData(eventDataBuffer, originalRequestId);
377
- yield result;
378
- eventDataBuffer = "";
379
- }
380
- } else if (line.startsWith("data:")) {
381
- eventDataBuffer += line.substring(5).trimStart() + "\n";
382
- } else if (line.startsWith(":")) {
383
- } else if (line.includes(":")) {
384
- }
385
- }
386
- }
387
- } catch (error) {
388
- console.error("Error reading or parsing SSE stream:", error.message);
389
- throw error;
390
- } finally {
391
- reader.releaseLock();
392
- }
393
- }
394
- /**
395
- * Processes a single SSE event's data string, expecting it to be a JSON-RPC response.
396
- * @param jsonData The string content from one or more 'data:' lines of an SSE event.
397
- * @param originalRequestId The ID of the client's request that initiated the stream.
398
- * @returns The `result` field of the parsed JSON-RPC success response.
399
- * @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.
400
- */
401
- _processSseEventData(jsonData, originalRequestId) {
402
- if (!jsonData.trim()) {
403
- throw new Error("Attempted to process empty SSE event data.");
404
- }
405
- try {
406
- const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\n$/, ""));
407
- const a2aStreamResponse = sseJsonRpcResponse;
408
- if (a2aStreamResponse.id !== originalRequestId) {
409
- console.warn(`SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`);
410
- }
411
- if (this.isErrorResponse(a2aStreamResponse)) {
412
- const err = a2aStreamResponse.error;
413
- throw new Error(`SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data || {})}`);
414
- }
415
- if (!("result" in a2aStreamResponse) || typeof a2aStreamResponse.result === "undefined") {
416
- throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
417
- }
418
- const successResponse = a2aStreamResponse;
419
- return successResponse.result;
420
- } catch (e) {
421
- if (e.message.startsWith("SSE event contained an error") || e.message.startsWith("SSE event JSON-RPC response is missing 'result' field")) {
422
- throw e;
423
- }
424
- console.error("Failed to parse SSE event data string or unexpected JSON-RPC structure:", jsonData, e);
425
- throw new Error(`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${e.message}`);
426
- }
677
+ this.transport = new JsonRpcTransport({ fetchImpl: this.customFetchImpl, endpoint });
678
+ return this.transport;
427
679
  }
428
- isErrorResponse(response) {
429
- return "error" in response;
430
- }
431
- ////////////////////////////////////////////////////////////////////////////////
432
- // Functions used to support old A2AClient Constructor to be deprecated soon
433
- // TODOs:
434
- // * remove `agentCardPromise`, and just use agentCard initialized
435
- // * _getServiceEndpoint can be made synchronous or deleted and accessed via
436
- // agentCard.url
437
- // * getAgentCard changed to this.agentCard
438
- // * delete resolveAgentCardUrl(), _fetchAndCacheAgentCard(),
439
- // agentCardPath from A2AClientOptions
440
- ////////////////////////////////////////////////////////////////////////////////
441
680
  /**
442
681
  * Fetches the Agent Card from the agent's well-known URI and caches its service endpoint URL.
443
682
  * This method is called by the constructor.
@@ -449,14 +688,18 @@ var A2AClient = class _A2AClient {
449
688
  try {
450
689
  const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
451
690
  const response = await this._fetch(agentCardUrl, {
452
- headers: { "Accept": "application/json" }
691
+ headers: { Accept: "application/json" }
453
692
  });
454
693
  if (!response.ok) {
455
- throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`);
694
+ throw new Error(
695
+ `Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
696
+ );
456
697
  }
457
698
  const agentCard = await response.json();
458
699
  if (!agentCard.url) {
459
- throw new Error("Fetched Agent Card does not contain a valid 'url' for the service endpoint.");
700
+ throw new Error(
701
+ "Fetched Agent Card does not contain a valid 'url' for the service endpoint."
702
+ );
460
703
  }
461
704
  this.serviceEndpointUrl = agentCard.url;
462
705
  return agentCard;
@@ -466,22 +709,24 @@ var A2AClient = class _A2AClient {
466
709
  }
467
710
  }
468
711
  /**
469
- * Retrieves the Agent Card.
470
- * If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
471
- * Otherwise, it returns the card fetched and cached during client construction.
472
- * @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
473
- * @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
474
- * If provided, this will fetch a new card, not use the cached one from the constructor's URL.
475
- * @returns A Promise that resolves to the AgentCard.
476
- */
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
+ */
477
720
  async getAgentCard(agentBaseUrl, agentCardPath) {
478
721
  if (agentBaseUrl) {
479
722
  const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
480
723
  const response = await this._fetch(agentCardUrl, {
481
- headers: { "Accept": "application/json" }
724
+ headers: { Accept: "application/json" }
482
725
  });
483
726
  if (!response.ok) {
484
- throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`);
727
+ throw new Error(
728
+ `Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
729
+ );
485
730
  }
486
731
  return await response.json();
487
732
  }
@@ -505,11 +750,39 @@ var A2AClient = class _A2AClient {
505
750
  }
506
751
  await this.agentCardPromise;
507
752
  if (!this.serviceEndpointUrl) {
508
- throw new Error("Agent Card URL for RPC endpoint is not available. Fetching might have failed.");
753
+ throw new Error(
754
+ "Agent Card URL for RPC endpoint is not available. Fetching might have failed."
755
+ );
509
756
  }
510
757
  return this.serviceEndpointUrl;
511
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
+ }
512
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
+ }
513
786
 
514
787
  // src/client/auth-handler.ts
515
788
  function createAuthenticatingFetchWithRetry(fetchImpl, authHandler) {
@@ -543,8 +816,774 @@ function createAuthenticatingFetchWithRetry(fetchImpl, authHandler) {
543
816
  Object.defineProperties(authFetch, Object.getOwnPropertyDescriptors(fetchImpl));
544
817
  return authFetch;
545
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
+ const factory = this.options.transports.find((t) => t.protocolName === transport);
1387
+ if (!factory) {
1388
+ throw new Error(
1389
+ `Unknown preferred transport: ${transport}, available transports: ${[...this.transportsByName.keys()].join()}`
1390
+ );
1391
+ }
1392
+ }
1393
+ this.agentCardResolver = options.cardResolver ?? AgentCardResolver.default;
1394
+ }
1395
+ transportsByName;
1396
+ agentCardResolver;
1397
+ /**
1398
+ * Creates a new client from the provided agent card.
1399
+ */
1400
+ async createFromAgentCard(agentCard) {
1401
+ const agentCardPreferred = agentCard.preferredTransport ?? JsonRpcTransportFactory.name;
1402
+ const additionalInterfaces = agentCard.additionalInterfaces ?? [];
1403
+ const urlsPerAgentTransports = new Map([
1404
+ [agentCardPreferred, agentCard.url],
1405
+ ...additionalInterfaces.map((i) => [i.transport, i.url])
1406
+ ]);
1407
+ const transportsByPreference = [
1408
+ ...this.options.preferredTransports ?? [],
1409
+ agentCardPreferred,
1410
+ ...additionalInterfaces.map((i) => i.transport)
1411
+ ];
1412
+ for (const transport of transportsByPreference) {
1413
+ if (!urlsPerAgentTransports.has(transport)) {
1414
+ continue;
1415
+ }
1416
+ const factory = this.transportsByName.get(transport);
1417
+ if (!factory) {
1418
+ continue;
1419
+ }
1420
+ return new Client(
1421
+ await factory.create(urlsPerAgentTransports.get(transport), agentCard),
1422
+ agentCard,
1423
+ this.options.clientConfig
1424
+ );
1425
+ }
1426
+ throw new Error(
1427
+ "No compatible transport found, available transports: " + [...this.transportsByName.keys()].join()
1428
+ );
1429
+ }
1430
+ /**
1431
+ * Downloads agent card using AgentCardResolver from options
1432
+ * and creates a new client from the downloaded card.
1433
+ *
1434
+ * @example
1435
+ * ```ts
1436
+ * const factory = new ClientFactory(); // use default options and default {@link AgentCardResolver}.
1437
+ * const client1 = await factory.createFromUrl('https://example.com'); // /.well-known/agent-card.json is used by default
1438
+ * const client2 = await factory.createFromUrl('https://example.com', '/my-agent-card.json'); // specify custom path
1439
+ * const client3 = await factory.createFromUrl('https://example.com/my-agent-card.json', ''); // specify full URL and set path to empty
1440
+ * ```
1441
+ */
1442
+ async createFromUrl(baseUrl, path) {
1443
+ const agentCard = await this.agentCardResolver.resolve(baseUrl, path);
1444
+ return this.createFromAgentCard(agentCard);
1445
+ }
1446
+ };
1447
+ function mergeTransports(original, overrides) {
1448
+ if (!overrides) {
1449
+ return original;
1450
+ }
1451
+ const result = transportsByName(original);
1452
+ const overridesByName = transportsByName(overrides);
1453
+ for (const [name, factory] of overridesByName) {
1454
+ result.set(name, factory);
1455
+ }
1456
+ return Array.from(result.values());
1457
+ }
1458
+ function transportsByName(transports) {
1459
+ const result = /* @__PURE__ */ new Map();
1460
+ if (!transports) {
1461
+ return result;
1462
+ }
1463
+ for (const t of transports) {
1464
+ if (result.has(t.protocolName)) {
1465
+ throw new Error(`Duplicate protocol name: ${t.protocolName}`);
1466
+ }
1467
+ result.set(t.protocolName, t);
1468
+ }
1469
+ return result;
1470
+ }
1471
+ function mergeArrays(a1, a2) {
1472
+ if (!a1 && !a2) {
1473
+ return void 0;
1474
+ }
1475
+ return [...a1 ?? [], ...a2 ?? []];
1476
+ }
1477
+
1478
+ // src/extensions.ts
1479
+ var Extensions = {
1480
+ /**
1481
+ * Creates new {@link Extensions} from `current` and `additional`.
1482
+ * If `current` already contains `additional` it is returned unmodified.
1483
+ */
1484
+ createFrom: (current, additional) => {
1485
+ if (current?.includes(additional)) {
1486
+ return current;
1487
+ }
1488
+ return [...current ?? [], additional];
1489
+ },
1490
+ /**
1491
+ * Creates {@link Extensions} from comma separated extensions identifiers as per
1492
+ * https://a2a-protocol.org/latest/specification/#326-service-parameters.
1493
+ * Parses the output of `toServiceParameter`.
1494
+ */
1495
+ parseServiceParameter: (value) => {
1496
+ if (!value) {
1497
+ return [];
1498
+ }
1499
+ const unique = new Set(
1500
+ value.split(",").map((ext) => ext.trim()).filter((ext) => ext.length > 0)
1501
+ );
1502
+ return Array.from(unique);
1503
+ },
1504
+ /**
1505
+ * Converts {@link Extensions} to comma separated extensions identifiers as per
1506
+ * https://a2a-protocol.org/latest/specification/#326-service-parameters.
1507
+ */
1508
+ toServiceParameter: (value) => {
1509
+ return value.join(",");
1510
+ }
1511
+ };
1512
+
1513
+ // src/client/service-parameters.ts
1514
+ var ServiceParameters = {
1515
+ create(...updates) {
1516
+ return ServiceParameters.createFrom(void 0, ...updates);
1517
+ },
1518
+ createFrom: (serviceParameters, ...updates) => {
1519
+ const result = serviceParameters ? { ...serviceParameters } : {};
1520
+ for (const update of updates) {
1521
+ update(result);
1522
+ }
1523
+ return result;
1524
+ }
1525
+ };
1526
+ function withA2AExtensions(...extensions) {
1527
+ return (parameters) => {
1528
+ parameters[HTTP_EXTENSION_HEADER] = Extensions.toServiceParameter(extensions);
1529
+ };
1530
+ }
1531
+
1532
+ // src/client/context.ts
1533
+ var ClientCallContext = {
1534
+ /**
1535
+ * Create a new {@link ClientCallContext} with optional updates applied.
1536
+ */
1537
+ create: (...updates) => {
1538
+ return ClientCallContext.createFrom(void 0, ...updates);
1539
+ },
1540
+ /**
1541
+ * Create a new {@link ClientCallContext} based on an existing one with updates applied.
1542
+ */
1543
+ createFrom: (context, ...updates) => {
1544
+ const result = context ? { ...context } : {};
1545
+ for (const update of updates) {
1546
+ update(result);
1547
+ }
1548
+ return result;
1549
+ }
1550
+ };
1551
+ var ClientCallContextKey = class {
1552
+ symbol;
1553
+ constructor(description) {
1554
+ this.symbol = Symbol(description);
1555
+ }
1556
+ set(value) {
1557
+ return (context) => {
1558
+ context[this.symbol] = value;
1559
+ };
1560
+ }
1561
+ get(context) {
1562
+ return context[this.symbol];
1563
+ }
1564
+ };
546
1565
  // Annotate the CommonJS export names for ESM import in node:
547
1566
  0 && (module.exports = {
548
1567
  A2AClient,
549
- createAuthenticatingFetchWithRetry
1568
+ AgentCardResolver,
1569
+ AuthenticatedExtendedCardNotConfiguredError,
1570
+ Client,
1571
+ ClientCallContext,
1572
+ ClientCallContextKey,
1573
+ ClientFactory,
1574
+ ClientFactoryOptions,
1575
+ ContentTypeNotSupportedError,
1576
+ DefaultAgentCardResolver,
1577
+ InvalidAgentResponseError,
1578
+ JsonRpcTransport,
1579
+ JsonRpcTransportFactory,
1580
+ PushNotificationNotSupportedError,
1581
+ RestTransport,
1582
+ RestTransportFactory,
1583
+ ServiceParameters,
1584
+ TaskNotCancelableError,
1585
+ TaskNotFoundError,
1586
+ UnsupportedOperationError,
1587
+ createAuthenticatingFetchWithRetry,
1588
+ withA2AExtensions
550
1589
  });