@mailmodo/a2a 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.
@@ -0,0 +1,122 @@
1
+ // src/errors.ts
2
+ var A2A_ERROR_CODE = {
3
+ PARSE_ERROR: -32700,
4
+ INVALID_REQUEST: -32600,
5
+ METHOD_NOT_FOUND: -32601,
6
+ INVALID_PARAMS: -32602,
7
+ INTERNAL_ERROR: -32603,
8
+ TASK_NOT_FOUND: -32001,
9
+ TASK_NOT_CANCELABLE: -32002,
10
+ PUSH_NOTIFICATION_NOT_SUPPORTED: -32003,
11
+ UNSUPPORTED_OPERATION: -32004,
12
+ CONTENT_TYPE_NOT_SUPPORTED: -32005,
13
+ INVALID_AGENT_RESPONSE: -32006,
14
+ AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED: -32007
15
+ };
16
+ var TaskNotFoundError = class extends Error {
17
+ constructor(message) {
18
+ super(message ?? "Task not found");
19
+ this.name = "TaskNotFoundError";
20
+ }
21
+ };
22
+ var TaskNotCancelableError = class extends Error {
23
+ constructor(message) {
24
+ super(message ?? "Task cannot be canceled");
25
+ this.name = "TaskNotCancelableError";
26
+ }
27
+ };
28
+ var PushNotificationNotSupportedError = class extends Error {
29
+ constructor(message) {
30
+ super(message ?? "Push Notification is not supported");
31
+ this.name = "PushNotificationNotSupportedError";
32
+ }
33
+ };
34
+ var UnsupportedOperationError = class extends Error {
35
+ constructor(message) {
36
+ super(message ?? "This operation is not supported");
37
+ this.name = "UnsupportedOperationError";
38
+ }
39
+ };
40
+ var ContentTypeNotSupportedError = class extends Error {
41
+ constructor(message) {
42
+ super(message ?? "Incompatible content types");
43
+ this.name = "ContentTypeNotSupportedError";
44
+ }
45
+ };
46
+ var InvalidAgentResponseError = class extends Error {
47
+ constructor(message) {
48
+ super(message ?? "Invalid agent response type");
49
+ this.name = "InvalidAgentResponseError";
50
+ }
51
+ };
52
+ var AuthenticatedExtendedCardNotConfiguredError = class extends Error {
53
+ constructor(message) {
54
+ super(message ?? "Authenticated Extended Card not configured");
55
+ this.name = "AuthenticatedExtendedCardNotConfiguredError";
56
+ }
57
+ };
58
+
59
+ // src/sse_utils.ts
60
+ var SSE_HEADERS = {
61
+ "Content-Type": "text/event-stream",
62
+ "Cache-Control": "no-cache",
63
+ Connection: "keep-alive",
64
+ "X-Accel-Buffering": "no"
65
+ // Disable buffering in nginx
66
+ };
67
+ function formatSSEEvent(event) {
68
+ return `data: ${JSON.stringify(event)}
69
+
70
+ `;
71
+ }
72
+ function formatSSEErrorEvent(error) {
73
+ return `event: error
74
+ data: ${JSON.stringify(error)}
75
+
76
+ `;
77
+ }
78
+ async function* parseSseStream(response) {
79
+ if (!response.body) {
80
+ throw new Error("SSE response body is undefined. Cannot read stream.");
81
+ }
82
+ let buffer = "";
83
+ let eventType = "message";
84
+ let eventData = "";
85
+ for await (const value of response.body.pipeThrough(new TextDecoderStream())) {
86
+ buffer += value;
87
+ let lineEndIndex;
88
+ while ((lineEndIndex = buffer.indexOf("\n")) >= 0) {
89
+ const line = buffer.substring(0, lineEndIndex).trim();
90
+ buffer = buffer.substring(lineEndIndex + 1);
91
+ if (line === "") {
92
+ if (eventData) {
93
+ yield { type: eventType, data: eventData };
94
+ eventData = "";
95
+ eventType = "message";
96
+ }
97
+ } else if (line.startsWith("event:")) {
98
+ eventType = line.substring("event:".length).trim();
99
+ } else if (line.startsWith("data:")) {
100
+ eventData = line.substring("data:".length).trim();
101
+ }
102
+ }
103
+ }
104
+ if (eventData) {
105
+ yield { type: eventType, data: eventData };
106
+ }
107
+ }
108
+
109
+ export {
110
+ A2A_ERROR_CODE,
111
+ TaskNotFoundError,
112
+ TaskNotCancelableError,
113
+ PushNotificationNotSupportedError,
114
+ UnsupportedOperationError,
115
+ ContentTypeNotSupportedError,
116
+ InvalidAgentResponseError,
117
+ AuthenticatedExtendedCardNotConfiguredError,
118
+ SSE_HEADERS,
119
+ formatSSEEvent,
120
+ formatSSEErrorEvent,
121
+ parseSseStream
122
+ };
@@ -1,6 +1,211 @@
1
- import { d as A2AStreamEventData, S as SendMessageResult } from '../auth-handler-DVLcl8yj.mjs';
2
- export { A as A2AClient, a as A2AClientOptions, b as AuthenticationHandler, H as HttpHeaders, c as createAuthenticatingFetchWithRetry } from '../auth-handler-DVLcl8yj.mjs';
3
- import { A as AgentCard, M as MessageSendParams, d as TaskPushNotificationConfig, a8 as GetTaskPushNotificationConfigParams, L as ListTaskPushNotificationConfigParams, D as DeleteTaskPushNotificationConfigParams, i as TaskQueryParams, T as Task, f as TaskIdParams, V as PushNotificationConfig, J as JSONRPCResponse } from '../types-Due_Cv6t.mjs';
1
+ import { ae as AgentCard, x as MessageSendParams, S as SendMessageResponse, F as Message, ay as Task, aQ as TaskStatusUpdateEvent, aS as TaskArtifactUpdateEvent, $ as TaskPushNotificationConfig, b as SetTaskPushNotificationConfigResponse, Z as TaskIdParams, c as GetTaskPushNotificationConfigResponse, a7 as ListTaskPushNotificationConfigParams, k as ListTaskPushNotificationConfigResponse, a9 as DeleteTaskPushNotificationConfigParams, h as DeleteTaskPushNotificationConfigResponse, X as TaskQueryParams, G as GetTaskResponse, C as CancelTaskResponse, j as JSONRPCResponse, E as Extensions, a3 as GetTaskPushNotificationConfigParams, z as PushNotificationConfig } from '../extensions-DvruCIzw.mjs';
2
+
3
+ type A2AStreamEventData = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
4
+ type SendMessageResult = Message | Task;
5
+ interface A2AClientOptions {
6
+ agentCardPath?: string;
7
+ fetchImpl?: typeof fetch;
8
+ }
9
+ /**
10
+ * A2AClient is a TypeScript HTTP client for interacting with A2A-compliant agents.
11
+ * Only JSON-RPC transport is supported.
12
+ * @deprecated Use {@link ClientFactory}
13
+ */
14
+ declare class A2AClient {
15
+ private static emptyOptions?;
16
+ private readonly agentCardPromise;
17
+ private readonly customFetchImpl?;
18
+ private serviceEndpointUrl?;
19
+ private transport?;
20
+ private requestIdCounter;
21
+ /**
22
+ * Constructs an A2AClient instance from an AgentCard.
23
+ * @param agentCard The AgentCard object.
24
+ * @param options Optional. The options for the A2AClient including the fetch/auth implementation.
25
+ */
26
+ constructor(agentCard: AgentCard | string, options?: A2AClientOptions);
27
+ /**
28
+ * Dynamically resolves the fetch implementation to use for requests.
29
+ * Prefers a custom implementation if provided, otherwise falls back to the global fetch.
30
+ * @returns The fetch implementation.
31
+ * @param args Arguments to pass to the fetch implementation.
32
+ * @throws If no fetch implementation is available.
33
+ */
34
+ private _fetch;
35
+ /**
36
+ * Creates an A2AClient instance by fetching the AgentCard from a URL then constructing the A2AClient.
37
+ * @param agentCardUrl The URL of the agent card.
38
+ * @param options Optional. The options for the A2AClient including the fetch/auth implementation.
39
+ * @returns A Promise that resolves to a new A2AClient instance.
40
+ */
41
+ static fromCardUrl(agentCardUrl: string, options?: A2AClientOptions): Promise<A2AClient>;
42
+ /**
43
+ * Sends a message to the agent.
44
+ * The behavior (blocking/non-blocking) and push notification configuration
45
+ * are specified within the `params.configuration` object.
46
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
47
+ * @param params The parameters for sending the message, including the message content and configuration.
48
+ * @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
49
+ */
50
+ sendMessage(params: MessageSendParams): Promise<SendMessageResponse>;
51
+ /**
52
+ * Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
53
+ * Push notification configuration can be specified in `params.configuration`.
54
+ * Optionally, `params.message.contextId` or `params.message.taskId` can be provided.
55
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
56
+ * @param params The parameters for sending the message.
57
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
58
+ * The generator throws an error if streaming is not supported or if an HTTP/SSE error occurs.
59
+ */
60
+ sendMessageStream(params: MessageSendParams): AsyncGenerator<A2AStreamEventData, void, undefined>;
61
+ /**
62
+ * Sets or updates the push notification configuration for a given task.
63
+ * Requires the agent to support push notifications (`capabilities.pushNotifications: true` in AgentCard).
64
+ * @param params Parameters containing the taskId and the TaskPushNotificationConfig.
65
+ * @returns A Promise resolving to SetTaskPushNotificationConfigResponse.
66
+ */
67
+ setTaskPushNotificationConfig(params: TaskPushNotificationConfig): Promise<SetTaskPushNotificationConfigResponse>;
68
+ /**
69
+ * Gets the push notification configuration for a given task.
70
+ * @param params Parameters containing the taskId.
71
+ * @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
72
+ */
73
+ getTaskPushNotificationConfig(params: TaskIdParams): Promise<GetTaskPushNotificationConfigResponse>;
74
+ /**
75
+ * Lists the push notification configurations for a given task.
76
+ * @param params Parameters containing the taskId.
77
+ * @returns A Promise resolving to ListTaskPushNotificationConfigResponse.
78
+ */
79
+ listTaskPushNotificationConfig(params: ListTaskPushNotificationConfigParams): Promise<ListTaskPushNotificationConfigResponse>;
80
+ /**
81
+ * Deletes the push notification configuration for a given task.
82
+ * @param params Parameters containing the taskId and push notification configuration ID.
83
+ * @returns A Promise resolving to DeleteTaskPushNotificationConfigResponse.
84
+ */
85
+ deleteTaskPushNotificationConfig(params: DeleteTaskPushNotificationConfigParams): Promise<DeleteTaskPushNotificationConfigResponse>;
86
+ /**
87
+ * Retrieves a task by its ID.
88
+ * @param params Parameters containing the taskId and optional historyLength.
89
+ * @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
90
+ */
91
+ getTask(params: TaskQueryParams): Promise<GetTaskResponse>;
92
+ /**
93
+ * Cancels a task by its ID.
94
+ * @param params Parameters containing the taskId.
95
+ * @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
96
+ */
97
+ cancelTask(params: TaskIdParams): Promise<CancelTaskResponse>;
98
+ /**
99
+ * @template TExtensionParams The type of parameters for the custom extension method.
100
+ * @template TExtensionResponse The type of response expected from the custom extension method.
101
+ * This should extend JSONRPCResponse. This ensures the extension response is still a valid A2A response.
102
+ * @param method Custom JSON-RPC method defined in the AgentCard's extensions.
103
+ * @param params Extension paramters defined in the AgentCard's extensions.
104
+ * @returns A Promise that resolves to the RPC response.
105
+ */
106
+ callExtensionMethod<TExtensionParams, TExtensionResponse extends JSONRPCResponse>(method: string, params: TExtensionParams): Promise<TExtensionResponse>;
107
+ /**
108
+ * Resubscribes to a task's event stream using Server-Sent Events (SSE).
109
+ * This is used if a previous SSE connection for an active task was broken.
110
+ * Requires the agent to support streaming (`capabilities.streaming: true` in AgentCard).
111
+ * @param params Parameters containing the taskId.
112
+ * @returns An AsyncGenerator yielding A2AStreamEventData (Message, Task, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent).
113
+ */
114
+ resubscribeTask(params: TaskIdParams): AsyncGenerator<A2AStreamEventData, void, undefined>;
115
+ private _getOrCreateTransport;
116
+ /**
117
+ * Fetches the Agent Card from the agent's well-known URI and caches its service endpoint URL.
118
+ * This method is called by the constructor.
119
+ * @param agentBaseUrl The base URL of the A2A agent (e.g., https://agent.example.com)
120
+ * @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
121
+ * @returns A Promise that resolves to the AgentCard.
122
+ */
123
+ private _fetchAndCacheAgentCard;
124
+ /**
125
+ * Retrieves the Agent Card.
126
+ * If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
127
+ * Otherwise, it returns the card fetched and cached during client construction.
128
+ * @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
129
+ * @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
130
+ * If provided, this will fetch a new card, not use the cached one from the constructor's URL.
131
+ * @returns A Promise that resolves to the AgentCard.
132
+ */
133
+ getAgentCard(agentBaseUrl?: string, agentCardPath?: string): Promise<AgentCard>;
134
+ /**
135
+ * Determines the agent card URL based on the agent URL.
136
+ * @param agentBaseUrl The agent URL.
137
+ * @param agentCardPath Optional relative path to the agent card, defaults to .well-known/agent-card.json
138
+ */
139
+ private resolveAgentCardUrl;
140
+ /**
141
+ * Gets the RPC service endpoint URL. Ensures the agent card has been fetched first.
142
+ * @returns A Promise that resolves to the service endpoint URL string.
143
+ */
144
+ private _getServiceEndpoint;
145
+ private invokeJsonRpc;
146
+ }
147
+
148
+ interface HttpHeaders {
149
+ [key: string]: string;
150
+ }
151
+ /**
152
+ * Generic interface for handling authentication for HTTP requests.
153
+ *
154
+ * - For each HTTP request, this handler is called to provide additional headers to the request through
155
+ * the headers() function.
156
+ * - After the server returns a response, the shouldRetryWithHeaders() function is called. Usually this
157
+ * function responds to a 401 or 403 response or JSON-RPC codes, but can respond to any other signal -
158
+ * that is an implementation detail of the AuthenticationHandler.
159
+ * - If the shouldRetryWithHeaders() function returns new headers, then the request should retried with the provided
160
+ * revised headers. These provisional headers may, or may not, be optimistically stored for subsequent requests -
161
+ * that is an implementation detail of the AuthenticationHandler.
162
+ * - If the request is successful and the onSuccessfulRetry() is defined, then the onSuccessfulRetry() function is
163
+ * called with the headers that were used to successfully complete the request. This callback provides an
164
+ * opportunity to save the headers for subsequent requests if they were not already saved.
165
+ *
166
+ */
167
+ interface AuthenticationHandler {
168
+ /**
169
+ * Provides additional HTTP request headers.
170
+ * @returns HTTP headers which may include Authorization if available.
171
+ */
172
+ headers: () => Promise<HttpHeaders>;
173
+ /**
174
+ * For every HTTP response (even 200s) the shouldRetryWithHeaders() method is called.
175
+ * This method is supposed to check if the request needs to be retried and if, yes,
176
+ * return a set of headers. An A2A server might indicate auth failures in its response
177
+ * by JSON-rpc codes, HTTP codes like 401, 403 or headers like WWW-Authenticate.
178
+ *
179
+ * @param req The RequestInit object used to invoke fetch()
180
+ * @param res The fetch Response object
181
+ * @returns If the HTTP request should be retried then returns the HTTP headers to use,
182
+ * or returns undefined if no retry should be made.
183
+ */
184
+ shouldRetryWithHeaders: (req: RequestInit, res: Response) => Promise<HttpHeaders | undefined>;
185
+ /**
186
+ * If the last HTTP request using the headers from shouldRetryWithHeaders() was successful, and
187
+ * this function is implemented, then it will be called with the headers provided from
188
+ * shouldRetryWithHeaders().
189
+ *
190
+ * This callback allows transient headers to be saved for subsequent requests only when they
191
+ * are validated by the server.
192
+ */
193
+ onSuccessfulRetry?: (headers: HttpHeaders) => Promise<void>;
194
+ }
195
+ /**
196
+ * Higher-order function that wraps fetch with authentication handling logic.
197
+ * Returns a new fetch function that automatically handles authentication retries for 401/403 responses.
198
+ *
199
+ * @param fetchImpl The underlying fetch implementation to wrap
200
+ * @param authHandler Authentication handler for managing auth headers and retries
201
+ * @returns A new fetch function with authentication handling capabilities
202
+ *
203
+ * Usage examples:
204
+ * - const authFetch = createAuthHandlingFetch(fetch, authHandler);
205
+ * - const response = await authFetch(url, options);
206
+ * - const response = await authFetch(url); // Direct function call
207
+ */
208
+ declare function createAuthenticatingFetchWithRetry(fetchImpl: typeof fetch, authHandler: AuthenticationHandler): typeof fetch;
4
209
 
5
210
  interface AgentCardResolverOptions {
6
211
  path?: string;
@@ -26,8 +231,45 @@ interface AgentCardResolver {
26
231
  resolve(baseUrl: string, path?: string): Promise<AgentCard>;
27
232
  }
28
233
  declare const AgentCardResolver: {
29
- Default: DefaultAgentCardResolver;
234
+ default: DefaultAgentCardResolver;
235
+ };
236
+
237
+ /**
238
+ * Function that applies an update to a {@link ClientCallContext}.
239
+ */
240
+ type ContextUpdate = (context: ClientCallContext) => void;
241
+ /**
242
+ * Opaque context object to carry per-call context data.
243
+ * Use {@link ClientCallContextKey} to create typed keys for storing and retrieving values.
244
+ */
245
+ type ClientCallContext = Record<symbol, unknown>;
246
+ declare const ClientCallContext: {
247
+ /**
248
+ * Create a new {@link ClientCallContext} with optional updates applied.
249
+ */
250
+ create: (...updates: ContextUpdate[]) => ClientCallContext;
251
+ /**
252
+ * Create a new {@link ClientCallContext} based on an existing one with updates applied.
253
+ */
254
+ createFrom: (context: ClientCallContext | undefined, ...updates: ContextUpdate[]) => ClientCallContext;
30
255
  };
256
+ /**
257
+ * Each instance represents a unique key for storing
258
+ * and retrieving typed values in a {@link ClientCallContext}.
259
+ *
260
+ * @example
261
+ * ```ts
262
+ * const key = new ClientCallContextKey<string>('My key');
263
+ * const context = ClientCallContext.create(key.set('example-value'));
264
+ * const value = key.get(context); // 'example-value'
265
+ * ```
266
+ */
267
+ declare class ClientCallContextKey<T> {
268
+ readonly symbol: symbol;
269
+ constructor(description: string);
270
+ set(value: T): ContextUpdate;
271
+ get(context: ClientCallContext): T | undefined;
272
+ }
31
273
 
32
274
  interface CallInterceptor {
33
275
  /**
@@ -45,6 +287,10 @@ interface BeforeArgs<K extends keyof Client = keyof Client> {
45
287
  * Payload inside the input object can be modified.
46
288
  */
47
289
  readonly input: ClientCallInput<K>;
290
+ /**
291
+ * Identifies the agent card cached on the client
292
+ */
293
+ readonly agentCard: AgentCard;
48
294
  /**
49
295
  * If set by the interceptor, stops execution, invokes "after"
50
296
  * for executed interceptors and returns the result. Transport is not called.
@@ -61,6 +307,10 @@ interface AfterArgs<K extends keyof Client = keyof Client> {
61
307
  * Payload inside the result object can be modified.
62
308
  */
63
309
  readonly result: ClientCallResult<K>;
310
+ /**
311
+ * Identifies the agent card cached on the client
312
+ */
313
+ readonly agentCard: AgentCard;
64
314
  /**
65
315
  * If set by the interceptor, stops execution and returns result value,
66
316
  * remaining interceptors are not executed.
@@ -92,7 +342,10 @@ type ClientCallResult<K extends keyof Client = keyof Client> = MethodResult<Clie
92
342
  * }
93
343
  */
94
344
  type MethodInput<T, TMembers extends keyof T = keyof T> = {
95
- [M in TMembers]: T[M] extends (payload: infer P) => unknown ? {
345
+ [M in TMembers]: T[M] extends (options: RequestOptions | undefined) => unknown ? {
346
+ readonly method: M;
347
+ value?: never;
348
+ } : T[M] extends (payload: infer P) => unknown ? {
96
349
  readonly method: M;
97
350
  value: P;
98
351
  } : never;
@@ -129,7 +382,16 @@ interface ResultsOverrides {
129
382
  resubscribeTask: A2AStreamEventData;
130
383
  }
131
384
 
385
+ type ServiceParametersUpdate = (parameters: ServiceParameters) => void;
386
+ type ServiceParameters = Record<string, string>;
387
+ declare const ServiceParameters: {
388
+ create(...updates: ServiceParametersUpdate[]): ServiceParameters;
389
+ createFrom: (serviceParameters: ServiceParameters | undefined, ...updates: ServiceParametersUpdate[]) => ServiceParameters;
390
+ };
391
+ declare function withA2AExtensions(...extensions: Extensions): ServiceParametersUpdate;
392
+
132
393
  interface Transport {
394
+ getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard>;
133
395
  sendMessage(params: MessageSendParams, options?: RequestOptions): Promise<SendMessageResult>;
134
396
  sendMessageStream(params: MessageSendParams, options?: RequestOptions): AsyncGenerator<A2AStreamEventData, void, undefined>;
135
397
  setTaskPushNotificationConfig(params: TaskPushNotificationConfig, options?: RequestOptions): Promise<TaskPushNotificationConfig>;
@@ -170,16 +432,26 @@ interface RequestOptions {
170
432
  * Signal to abort request execution.
171
433
  */
172
434
  signal?: AbortSignal;
435
+ /**
436
+ * A key-value map for passing horizontally applicable context or parameters.
437
+ * All parameters are passed to the server via underlying transports (e.g. In JsonRPC via Headers).
438
+ */
439
+ serviceParameters?: ServiceParameters;
173
440
  /**
174
441
  * Arbitrary data available to interceptors and transport implementation.
175
442
  */
176
- context?: Map<string, unknown>;
443
+ context?: ClientCallContext;
177
444
  }
178
445
  declare class Client {
179
446
  readonly transport: Transport;
180
- readonly agentCard: AgentCard;
447
+ private agentCard;
181
448
  readonly config?: ClientConfig;
182
449
  constructor(transport: Transport, agentCard: AgentCard, config?: ClientConfig);
450
+ /**
451
+ * If the current agent card supports the extended feature, it will try to fetch the extended agent card from the server,
452
+ * Otherwise it will return the current agent card value.
453
+ */
454
+ getAgentCard(options?: RequestOptions): Promise<AgentCard>;
183
455
  /**
184
456
  * Sends a message to an agent to initiate a new interaction or to continue an existing one.
185
457
  * Uses blocking mode by default.
@@ -230,6 +502,92 @@ declare class Client {
230
502
 
231
503
  type TransportProtocolName = 'JSONRPC' | 'HTTP+JSON' | 'GRPC' | (string & {});
232
504
 
505
+ interface ClientFactoryOptions {
506
+ /**
507
+ * Transport factories to use.
508
+ * Effectively defines transports supported by this client factory.
509
+ */
510
+ transports: TransportFactory[];
511
+ /**
512
+ * Client config to be used for clients created by this factory.
513
+ */
514
+ clientConfig?: ClientConfig;
515
+ /**
516
+ * Transport preferences to override ones defined by the agent card.
517
+ * If no matches are found among preferred transports, agent card values are used next.
518
+ */
519
+ preferredTransports?: TransportProtocolName[];
520
+ /**
521
+ * Used for createFromAgentCardUrl to download agent card.
522
+ */
523
+ cardResolver?: AgentCardResolver;
524
+ }
525
+ declare const ClientFactoryOptions: {
526
+ /**
527
+ * SDK default options for {@link ClientFactory}.
528
+ */
529
+ default: Readonly<ClientFactoryOptions>;
530
+ /**
531
+ * Creates new options by merging an original and an override object.
532
+ * Transports are merged based on `TransportFactory.protocolName`,
533
+ * interceptors are concatenated, other fields are overriden.
534
+ *
535
+ * @example
536
+ * ```ts
537
+ * const options = ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
538
+ * transports: [new MyCustomTransportFactory()], // adds a custom transport
539
+ * clientConfig: { interceptors: [new MyInterceptor()] }, // adds a custom interceptor
540
+ * });
541
+ * ```
542
+ */
543
+ createFrom(original: ClientFactoryOptions, overrides: Partial<ClientFactoryOptions>): ClientFactoryOptions;
544
+ };
545
+ declare class ClientFactory {
546
+ readonly options: ClientFactoryOptions;
547
+ private readonly transportsByName;
548
+ private readonly agentCardResolver;
549
+ constructor(options?: ClientFactoryOptions);
550
+ /**
551
+ * Creates a new client from the provided agent card.
552
+ */
553
+ createFromAgentCard(agentCard: AgentCard): Promise<Client>;
554
+ /**
555
+ * Downloads agent card using AgentCardResolver from options
556
+ * and creates a new client from the downloaded card.
557
+ *
558
+ * @example
559
+ * ```ts
560
+ * const factory = new ClientFactory(); // use default options and default {@link AgentCardResolver}.
561
+ * const client1 = await factory.createFromUrl('https://example.com'); // /.well-known/agent-card.json is used by default
562
+ * const client2 = await factory.createFromUrl('https://example.com', '/my-agent-card.json'); // specify custom path
563
+ * const client3 = await factory.createFromUrl('https://example.com/my-agent-card.json', ''); // specify full URL and set path to empty
564
+ * ```
565
+ */
566
+ createFromUrl(baseUrl: string, path?: string): Promise<Client>;
567
+ }
568
+
569
+ declare class TaskNotFoundError extends Error {
570
+ constructor(message?: string);
571
+ }
572
+ declare class TaskNotCancelableError extends Error {
573
+ constructor(message?: string);
574
+ }
575
+ declare class PushNotificationNotSupportedError extends Error {
576
+ constructor(message?: string);
577
+ }
578
+ declare class UnsupportedOperationError extends Error {
579
+ constructor(message?: string);
580
+ }
581
+ declare class ContentTypeNotSupportedError extends Error {
582
+ constructor(message?: string);
583
+ }
584
+ declare class InvalidAgentResponseError extends Error {
585
+ constructor(message?: string);
586
+ }
587
+ declare class AuthenticatedExtendedCardNotConfiguredError extends Error {
588
+ constructor(message?: string);
589
+ }
590
+
233
591
  interface JsonRpcTransportOptions {
234
592
  endpoint: string;
235
593
  fetchImpl?: typeof fetch;
@@ -239,6 +597,7 @@ declare class JsonRpcTransport implements Transport {
239
597
  private readonly endpoint;
240
598
  private requestIdCounter;
241
599
  constructor(options: JsonRpcTransportOptions);
600
+ getExtendedAgentCard(options?: RequestOptions, idOverride?: number): Promise<AgentCard>;
242
601
  sendMessage(params: MessageSendParams, options?: RequestOptions, idOverride?: number): Promise<SendMessageResult>;
243
602
  sendMessageStream(params: MessageSendParams, options?: RequestOptions): AsyncGenerator<A2AStreamEventData, void, undefined>;
244
603
  setTaskPushNotificationConfig(params: TaskPushNotificationConfig, options?: RequestOptions, idOverride?: number): Promise<TaskPushNotificationConfig>;
@@ -253,7 +612,6 @@ declare class JsonRpcTransport implements Transport {
253
612
  private _sendRpcRequest;
254
613
  private _fetchRpc;
255
614
  private _sendStreamingRequest;
256
- private _parseA2ASseStream;
257
615
  private _processSseEventData;
258
616
  private static mapToError;
259
617
  }
@@ -268,45 +626,41 @@ declare class JsonRpcTransportFactory implements TransportFactory {
268
626
  create(url: string, _agentCard: AgentCard): Promise<Transport>;
269
627
  }
270
628
 
271
- interface ClientFactoryOptions {
272
- /**
273
- * Transport factories to use.
274
- * Effectively defines transports supported by this client factory.
275
- */
276
- transports: ReadonlyArray<TransportFactory>;
277
- /**
278
- * Client config to be used for clients created by this factory.
279
- */
280
- clientConfig?: ClientConfig;
281
- /**
282
- * Transport preferences to override ones defined by the agent card.
283
- * If no matches are found among preferred transports, agent card values are used next.
284
- */
285
- preferredTransports?: TransportProtocolName[];
286
- /**
287
- * Used for createFromAgentCardUrl to download agent card.
288
- */
289
- cardResolver?: AgentCardResolver;
629
+ interface RestTransportOptions {
630
+ endpoint: string;
631
+ fetchImpl?: typeof fetch;
290
632
  }
291
- declare const ClientFactoryOptions: {
292
- Default: {
293
- transports: JsonRpcTransportFactory[];
294
- };
295
- };
296
- declare class ClientFactory {
297
- readonly options: ClientFactoryOptions;
298
- private readonly transportsByName;
299
- private readonly agentCardResolver;
300
- constructor(options?: ClientFactoryOptions);
301
- /**
302
- * Creates a new client from the provided agent card.
303
- */
304
- createFromAgentCard(agentCard: AgentCard): Promise<Client>;
305
- /**
306
- * Downloads agent card using AgentCardResolver from options
307
- * and creates a new client from the downloaded card.
308
- */
309
- createFromAgentCardUrl(baseUrl: string, path?: string): Promise<Client>;
633
+ declare class RestTransport implements Transport {
634
+ private readonly customFetchImpl?;
635
+ private readonly endpoint;
636
+ constructor(options: RestTransportOptions);
637
+ getExtendedAgentCard(options?: RequestOptions): Promise<AgentCard>;
638
+ sendMessage(params: MessageSendParams, options?: RequestOptions): Promise<SendMessageResult>;
639
+ sendMessageStream(params: MessageSendParams, options?: RequestOptions): AsyncGenerator<A2AStreamEventData, void, undefined>;
640
+ setTaskPushNotificationConfig(params: TaskPushNotificationConfig, options?: RequestOptions): Promise<TaskPushNotificationConfig>;
641
+ getTaskPushNotificationConfig(params: GetTaskPushNotificationConfigParams, options?: RequestOptions): Promise<TaskPushNotificationConfig>;
642
+ listTaskPushNotificationConfig(params: ListTaskPushNotificationConfigParams, options?: RequestOptions): Promise<TaskPushNotificationConfig[]>;
643
+ deleteTaskPushNotificationConfig(params: DeleteTaskPushNotificationConfigParams, options?: RequestOptions): Promise<void>;
644
+ getTask(params: TaskQueryParams, options?: RequestOptions): Promise<Task>;
645
+ cancelTask(params: TaskIdParams, options?: RequestOptions): Promise<Task>;
646
+ resubscribeTask(params: TaskIdParams, options?: RequestOptions): AsyncGenerator<A2AStreamEventData, void, undefined>;
647
+ private _fetch;
648
+ private _buildHeaders;
649
+ private _sendRequest;
650
+ private _handleErrorResponse;
651
+ private _sendStreamingRequest;
652
+ private _processSseEventData;
653
+ private static mapToError;
654
+ }
655
+ interface RestTransportFactoryOptions {
656
+ fetchImpl?: typeof fetch;
657
+ }
658
+ declare class RestTransportFactory implements TransportFactory {
659
+ private readonly options?;
660
+ static readonly name: TransportProtocolName;
661
+ constructor(options?: RestTransportFactoryOptions);
662
+ get protocolName(): string;
663
+ create(url: string, _agentCard: AgentCard): Promise<Transport>;
310
664
  }
311
665
 
312
- export { type AfterArgs, AgentCardResolver, type AgentCardResolverOptions, type BeforeArgs, type CallInterceptor, Client, type ClientCallInput, type ClientCallResult, type ClientConfig, ClientFactory, ClientFactoryOptions, DefaultAgentCardResolver, JsonRpcTransport, JsonRpcTransportFactory, type JsonRpcTransportOptions, type RequestOptions, type Transport, type TransportFactory };
666
+ export { A2AClient, type A2AClientOptions, type AfterArgs, AgentCardResolver, type AgentCardResolverOptions, AuthenticatedExtendedCardNotConfiguredError, type AuthenticationHandler, type BeforeArgs, type CallInterceptor, Client, ClientCallContext, ClientCallContextKey, type ClientCallInput, type ClientCallResult, type ClientConfig, ClientFactory, ClientFactoryOptions, ContentTypeNotSupportedError, type ContextUpdate, DefaultAgentCardResolver, type HttpHeaders, InvalidAgentResponseError, JsonRpcTransport, JsonRpcTransportFactory, type JsonRpcTransportOptions, PushNotificationNotSupportedError, type RequestOptions, RestTransport, RestTransportFactory, type RestTransportOptions, ServiceParameters, type ServiceParametersUpdate, TaskNotCancelableError, TaskNotFoundError, type Transport, type TransportFactory, UnsupportedOperationError, createAuthenticatingFetchWithRetry, withA2AExtensions };