@a2a-js/sdk 0.3.4 → 0.3.6
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.
- package/README.md +258 -188
- package/dist/a2a_request_handler-B3LxMq3P.d.cts +49 -0
- package/dist/a2a_request_handler-BuP9LgXH.d.ts +49 -0
- package/dist/chunk-3QDLXHKS.js +8 -0
- package/dist/{chunk-JA52GYRU.js → chunk-LTPINR5K.js} +115 -61
- package/dist/chunk-ZX6KNMCP.js +38 -0
- package/dist/client/index.cjs +1057 -256
- package/dist/client/index.d.cts +419 -48
- package/dist/client/index.d.ts +419 -48
- package/dist/client/index.js +1015 -257
- package/dist/{types-DNKcmF0f.d.cts → extensions-DvruCIzw.d.cts} +28 -1
- package/dist/{types-DNKcmF0f.d.ts → extensions-DvruCIzw.d.ts} +28 -1
- package/dist/index.cjs +42 -2
- package/dist/index.d.cts +7 -3
- package/dist/index.d.ts +7 -3
- package/dist/index.js +9 -3
- package/dist/server/express/index.cjs +790 -141
- package/dist/server/express/index.d.cts +84 -7
- package/dist/server/express/index.d.ts +84 -7
- package/dist/server/express/index.js +651 -82
- package/dist/server/index.cjs +368 -145
- package/dist/server/index.d.cts +36 -26
- package/dist/server/index.d.ts +36 -26
- package/dist/server/index.js +227 -86
- package/package.json +17 -9
- package/dist/a2a_request_handler-B5t-IxgA.d.ts +0 -17
- package/dist/a2a_request_handler-DUvKWfix.d.cts +0 -17
- package/dist/chunk-67JNQ6TZ.js +0 -6
package/dist/client/index.js
CHANGED
|
@@ -1,14 +1,409 @@
|
|
|
1
1
|
import {
|
|
2
|
-
AGENT_CARD_PATH
|
|
3
|
-
|
|
2
|
+
AGENT_CARD_PATH,
|
|
3
|
+
HTTP_EXTENSION_HEADER
|
|
4
|
+
} from "../chunk-3QDLXHKS.js";
|
|
5
|
+
import {
|
|
6
|
+
Extensions
|
|
7
|
+
} from "../chunk-ZX6KNMCP.js";
|
|
8
|
+
|
|
9
|
+
// src/errors.ts
|
|
10
|
+
var TaskNotFoundError = class extends Error {
|
|
11
|
+
constructor(message) {
|
|
12
|
+
super(message ?? "Task not found");
|
|
13
|
+
this.name = "TaskNotFoundError";
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
var TaskNotCancelableError = class extends Error {
|
|
17
|
+
constructor(message) {
|
|
18
|
+
super(message ?? "Task cannot be canceled");
|
|
19
|
+
this.name = "TaskNotCancelableError";
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
var PushNotificationNotSupportedError = class extends Error {
|
|
23
|
+
constructor(message) {
|
|
24
|
+
super(message ?? "Push Notification is not supported");
|
|
25
|
+
this.name = "PushNotificationNotSupportedError";
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
var UnsupportedOperationError = class extends Error {
|
|
29
|
+
constructor(message) {
|
|
30
|
+
super(message ?? "This operation is not supported");
|
|
31
|
+
this.name = "UnsupportedOperationError";
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
var ContentTypeNotSupportedError = class extends Error {
|
|
35
|
+
constructor(message) {
|
|
36
|
+
super(message ?? "Incompatible content types");
|
|
37
|
+
this.name = "ContentTypeNotSupportedError";
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
var InvalidAgentResponseError = class extends Error {
|
|
41
|
+
constructor(message) {
|
|
42
|
+
super(message ?? "Invalid agent response type");
|
|
43
|
+
this.name = "InvalidAgentResponseError";
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
var AuthenticatedExtendedCardNotConfiguredError = class extends Error {
|
|
47
|
+
constructor(message) {
|
|
48
|
+
super(message ?? "Authenticated Extended Card not configured");
|
|
49
|
+
this.name = "AuthenticatedExtendedCardNotConfiguredError";
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// src/client/transports/json_rpc_transport.ts
|
|
54
|
+
var JsonRpcTransport = class _JsonRpcTransport {
|
|
55
|
+
customFetchImpl;
|
|
56
|
+
endpoint;
|
|
57
|
+
requestIdCounter = 1;
|
|
58
|
+
constructor(options) {
|
|
59
|
+
this.endpoint = options.endpoint;
|
|
60
|
+
this.customFetchImpl = options.fetchImpl;
|
|
61
|
+
}
|
|
62
|
+
async getExtendedAgentCard(options, idOverride) {
|
|
63
|
+
const rpcResponse = await this._sendRpcRequest("agent/getAuthenticatedExtendedCard", void 0, idOverride, options);
|
|
64
|
+
return rpcResponse.result;
|
|
65
|
+
}
|
|
66
|
+
async sendMessage(params, options, idOverride) {
|
|
67
|
+
const rpcResponse = await this._sendRpcRequest(
|
|
68
|
+
"message/send",
|
|
69
|
+
params,
|
|
70
|
+
idOverride,
|
|
71
|
+
options
|
|
72
|
+
);
|
|
73
|
+
return rpcResponse.result;
|
|
74
|
+
}
|
|
75
|
+
async *sendMessageStream(params, options) {
|
|
76
|
+
yield* this._sendStreamingRequest("message/stream", params, options);
|
|
77
|
+
}
|
|
78
|
+
async setTaskPushNotificationConfig(params, options, idOverride) {
|
|
79
|
+
const rpcResponse = await this._sendRpcRequest("tasks/pushNotificationConfig/set", params, idOverride, options);
|
|
80
|
+
return rpcResponse.result;
|
|
81
|
+
}
|
|
82
|
+
async getTaskPushNotificationConfig(params, options, idOverride) {
|
|
83
|
+
const rpcResponse = await this._sendRpcRequest("tasks/pushNotificationConfig/get", params, idOverride, options);
|
|
84
|
+
return rpcResponse.result;
|
|
85
|
+
}
|
|
86
|
+
async listTaskPushNotificationConfig(params, options, idOverride) {
|
|
87
|
+
const rpcResponse = await this._sendRpcRequest("tasks/pushNotificationConfig/list", params, idOverride, options);
|
|
88
|
+
return rpcResponse.result;
|
|
89
|
+
}
|
|
90
|
+
async deleteTaskPushNotificationConfig(params, options, idOverride) {
|
|
91
|
+
await this._sendRpcRequest("tasks/pushNotificationConfig/delete", params, idOverride, options);
|
|
92
|
+
}
|
|
93
|
+
async getTask(params, options, idOverride) {
|
|
94
|
+
const rpcResponse = await this._sendRpcRequest(
|
|
95
|
+
"tasks/get",
|
|
96
|
+
params,
|
|
97
|
+
idOverride,
|
|
98
|
+
options
|
|
99
|
+
);
|
|
100
|
+
return rpcResponse.result;
|
|
101
|
+
}
|
|
102
|
+
async cancelTask(params, options, idOverride) {
|
|
103
|
+
const rpcResponse = await this._sendRpcRequest(
|
|
104
|
+
"tasks/cancel",
|
|
105
|
+
params,
|
|
106
|
+
idOverride,
|
|
107
|
+
options
|
|
108
|
+
);
|
|
109
|
+
return rpcResponse.result;
|
|
110
|
+
}
|
|
111
|
+
async *resubscribeTask(params, options) {
|
|
112
|
+
yield* this._sendStreamingRequest("tasks/resubscribe", params, options);
|
|
113
|
+
}
|
|
114
|
+
async callExtensionMethod(method, params, idOverride, options) {
|
|
115
|
+
return await this._sendRpcRequest(
|
|
116
|
+
method,
|
|
117
|
+
params,
|
|
118
|
+
idOverride,
|
|
119
|
+
options
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
_fetch(...args) {
|
|
123
|
+
if (this.customFetchImpl) {
|
|
124
|
+
return this.customFetchImpl(...args);
|
|
125
|
+
}
|
|
126
|
+
if (typeof fetch === "function") {
|
|
127
|
+
return fetch(...args);
|
|
128
|
+
}
|
|
129
|
+
throw new Error(
|
|
130
|
+
"A `fetch` implementation was not provided and is not available in the global scope. Please provide a `fetchImpl` in the A2ATransportOptions. "
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
async _sendRpcRequest(method, params, idOverride, options) {
|
|
134
|
+
const requestId = idOverride ?? this.requestIdCounter++;
|
|
135
|
+
const rpcRequest = {
|
|
136
|
+
jsonrpc: "2.0",
|
|
137
|
+
method,
|
|
138
|
+
params,
|
|
139
|
+
id: requestId
|
|
140
|
+
};
|
|
141
|
+
const httpResponse = await this._fetchRpc(rpcRequest, "application/json", options);
|
|
142
|
+
if (!httpResponse.ok) {
|
|
143
|
+
let errorBodyText = "(empty or non-JSON response)";
|
|
144
|
+
let errorJson;
|
|
145
|
+
try {
|
|
146
|
+
errorBodyText = await httpResponse.text();
|
|
147
|
+
errorJson = JSON.parse(errorBodyText);
|
|
148
|
+
} catch (e) {
|
|
149
|
+
throw new Error(
|
|
150
|
+
`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`,
|
|
151
|
+
{ cause: e }
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
if (errorJson.jsonrpc && errorJson.error) {
|
|
155
|
+
throw _JsonRpcTransport.mapToError(errorJson);
|
|
156
|
+
} else {
|
|
157
|
+
throw new Error(
|
|
158
|
+
`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const rpcResponse = await httpResponse.json();
|
|
163
|
+
if (rpcResponse.id !== requestId) {
|
|
164
|
+
console.error(
|
|
165
|
+
`CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}.`
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
if ("error" in rpcResponse) {
|
|
169
|
+
throw _JsonRpcTransport.mapToError(rpcResponse);
|
|
170
|
+
}
|
|
171
|
+
return rpcResponse;
|
|
172
|
+
}
|
|
173
|
+
async _fetchRpc(rpcRequest, acceptHeader = "application/json", options) {
|
|
174
|
+
const requestInit = {
|
|
175
|
+
method: "POST",
|
|
176
|
+
headers: {
|
|
177
|
+
...options?.serviceParameters,
|
|
178
|
+
"Content-Type": "application/json",
|
|
179
|
+
Accept: acceptHeader
|
|
180
|
+
},
|
|
181
|
+
body: JSON.stringify(rpcRequest),
|
|
182
|
+
signal: options?.signal
|
|
183
|
+
};
|
|
184
|
+
return this._fetch(this.endpoint, requestInit);
|
|
185
|
+
}
|
|
186
|
+
async *_sendStreamingRequest(method, params, options) {
|
|
187
|
+
const clientRequestId = this.requestIdCounter++;
|
|
188
|
+
const rpcRequest = {
|
|
189
|
+
jsonrpc: "2.0",
|
|
190
|
+
method,
|
|
191
|
+
params,
|
|
192
|
+
id: clientRequestId
|
|
193
|
+
};
|
|
194
|
+
const response = await this._fetchRpc(rpcRequest, "text/event-stream", options);
|
|
195
|
+
if (!response.ok) {
|
|
196
|
+
let errorBody = "";
|
|
197
|
+
let errorJson;
|
|
198
|
+
try {
|
|
199
|
+
errorBody = await response.text();
|
|
200
|
+
errorJson = JSON.parse(errorBody);
|
|
201
|
+
} catch (e) {
|
|
202
|
+
throw new Error(
|
|
203
|
+
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}. Response: ${errorBody || "(empty)"}`,
|
|
204
|
+
{ cause: e }
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
if (errorJson.error) {
|
|
208
|
+
throw new Error(
|
|
209
|
+
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
throw new Error(
|
|
213
|
+
`HTTP error establishing stream for ${method}: ${response.status} ${response.statusText}`
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
|
|
217
|
+
throw new Error(
|
|
218
|
+
`Invalid response Content-Type for SSE stream for ${method}. Expected 'text/event-stream'.`
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
yield* this._parseA2ASseStream(response, clientRequestId);
|
|
222
|
+
}
|
|
223
|
+
async *_parseA2ASseStream(response, originalRequestId) {
|
|
224
|
+
if (!response.body) {
|
|
225
|
+
throw new Error("SSE response body is undefined. Cannot read stream.");
|
|
226
|
+
}
|
|
227
|
+
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
228
|
+
let buffer = "";
|
|
229
|
+
let eventDataBuffer = "";
|
|
230
|
+
try {
|
|
231
|
+
while (true) {
|
|
232
|
+
const { done, value } = await reader.read();
|
|
233
|
+
if (done) {
|
|
234
|
+
if (eventDataBuffer.trim()) {
|
|
235
|
+
const result = this._processSseEventData(
|
|
236
|
+
eventDataBuffer,
|
|
237
|
+
originalRequestId
|
|
238
|
+
);
|
|
239
|
+
yield result;
|
|
240
|
+
}
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
buffer += value;
|
|
244
|
+
let lineEndIndex;
|
|
245
|
+
while ((lineEndIndex = buffer.indexOf("\n")) >= 0) {
|
|
246
|
+
const line = buffer.substring(0, lineEndIndex).trim();
|
|
247
|
+
buffer = buffer.substring(lineEndIndex + 1);
|
|
248
|
+
if (line === "") {
|
|
249
|
+
if (eventDataBuffer) {
|
|
250
|
+
const result = this._processSseEventData(
|
|
251
|
+
eventDataBuffer,
|
|
252
|
+
originalRequestId
|
|
253
|
+
);
|
|
254
|
+
yield result;
|
|
255
|
+
eventDataBuffer = "";
|
|
256
|
+
}
|
|
257
|
+
} else if (line.startsWith("data:")) {
|
|
258
|
+
eventDataBuffer += line.substring(5).trimStart() + "\n";
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
} catch (error) {
|
|
263
|
+
console.error(
|
|
264
|
+
"Error reading or parsing SSE stream:",
|
|
265
|
+
error instanceof Error && error.message || "Error unknown"
|
|
266
|
+
);
|
|
267
|
+
throw error;
|
|
268
|
+
} finally {
|
|
269
|
+
reader.releaseLock();
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
_processSseEventData(jsonData, originalRequestId) {
|
|
273
|
+
if (!jsonData.trim()) {
|
|
274
|
+
throw new Error("Attempted to process empty SSE event data.");
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\n$/, ""));
|
|
278
|
+
const a2aStreamResponse = sseJsonRpcResponse;
|
|
279
|
+
if (a2aStreamResponse.id !== originalRequestId) {
|
|
280
|
+
console.warn(
|
|
281
|
+
`SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
if ("error" in a2aStreamResponse) {
|
|
285
|
+
const err = a2aStreamResponse.error;
|
|
286
|
+
throw new Error(
|
|
287
|
+
`SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data || {})}`
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
if (!("result" in a2aStreamResponse) || typeof a2aStreamResponse.result === "undefined") {
|
|
291
|
+
throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
|
|
292
|
+
}
|
|
293
|
+
return a2aStreamResponse.result;
|
|
294
|
+
} catch (e) {
|
|
295
|
+
if (e instanceof Error && (e.message.startsWith("SSE event contained an error") || e.message.startsWith("SSE event JSON-RPC response is missing 'result' field"))) {
|
|
296
|
+
throw e;
|
|
297
|
+
}
|
|
298
|
+
console.error(
|
|
299
|
+
"Failed to parse SSE event data string or unexpected JSON-RPC structure:",
|
|
300
|
+
jsonData,
|
|
301
|
+
e
|
|
302
|
+
);
|
|
303
|
+
throw new Error(
|
|
304
|
+
`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${e instanceof Error && e.message || "Unknown error"}`
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
static mapToError(response) {
|
|
309
|
+
switch (response.error.code) {
|
|
310
|
+
case -32001:
|
|
311
|
+
return new TaskNotFoundJSONRPCError(response);
|
|
312
|
+
case -32002:
|
|
313
|
+
return new TaskNotCancelableJSONRPCError(response);
|
|
314
|
+
case -32003:
|
|
315
|
+
return new PushNotificationNotSupportedJSONRPCError(response);
|
|
316
|
+
case -32004:
|
|
317
|
+
return new UnsupportedOperationJSONRPCError(response);
|
|
318
|
+
case -32005:
|
|
319
|
+
return new ContentTypeNotSupportedJSONRPCError(response);
|
|
320
|
+
case -32006:
|
|
321
|
+
return new InvalidAgentResponseJSONRPCError(response);
|
|
322
|
+
case -32007:
|
|
323
|
+
return new AuthenticatedExtendedCardNotConfiguredJSONRPCError(response);
|
|
324
|
+
default:
|
|
325
|
+
return new JSONRPCTransportError(response);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
var JsonRpcTransportFactory = class _JsonRpcTransportFactory {
|
|
330
|
+
constructor(options) {
|
|
331
|
+
this.options = options;
|
|
332
|
+
}
|
|
333
|
+
static name = "JSONRPC";
|
|
334
|
+
get protocolName() {
|
|
335
|
+
return _JsonRpcTransportFactory.name;
|
|
336
|
+
}
|
|
337
|
+
async create(url, _agentCard) {
|
|
338
|
+
return new JsonRpcTransport({
|
|
339
|
+
endpoint: url,
|
|
340
|
+
fetchImpl: this.options?.fetchImpl
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
var JSONRPCTransportError = class extends Error {
|
|
345
|
+
constructor(errorResponse) {
|
|
346
|
+
super(
|
|
347
|
+
`JSON-RPC error: ${errorResponse.error.message} (Code: ${errorResponse.error.code}) Data: ${JSON.stringify(errorResponse.error.data || {})}`
|
|
348
|
+
);
|
|
349
|
+
this.errorResponse = errorResponse;
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
var TaskNotFoundJSONRPCError = class extends TaskNotFoundError {
|
|
353
|
+
constructor(errorResponse) {
|
|
354
|
+
super();
|
|
355
|
+
this.errorResponse = errorResponse;
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
var TaskNotCancelableJSONRPCError = class extends TaskNotCancelableError {
|
|
359
|
+
constructor(errorResponse) {
|
|
360
|
+
super();
|
|
361
|
+
this.errorResponse = errorResponse;
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
var PushNotificationNotSupportedJSONRPCError = class extends PushNotificationNotSupportedError {
|
|
365
|
+
constructor(errorResponse) {
|
|
366
|
+
super();
|
|
367
|
+
this.errorResponse = errorResponse;
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
var UnsupportedOperationJSONRPCError = class extends UnsupportedOperationError {
|
|
371
|
+
constructor(errorResponse) {
|
|
372
|
+
super();
|
|
373
|
+
this.errorResponse = errorResponse;
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
var ContentTypeNotSupportedJSONRPCError = class extends ContentTypeNotSupportedError {
|
|
377
|
+
constructor(errorResponse) {
|
|
378
|
+
super();
|
|
379
|
+
this.errorResponse = errorResponse;
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
var InvalidAgentResponseJSONRPCError = class extends InvalidAgentResponseError {
|
|
383
|
+
constructor(errorResponse) {
|
|
384
|
+
super();
|
|
385
|
+
this.errorResponse = errorResponse;
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
var AuthenticatedExtendedCardNotConfiguredJSONRPCError = class extends AuthenticatedExtendedCardNotConfiguredError {
|
|
389
|
+
constructor(errorResponse) {
|
|
390
|
+
super();
|
|
391
|
+
this.errorResponse = errorResponse;
|
|
392
|
+
}
|
|
393
|
+
};
|
|
4
394
|
|
|
5
395
|
// src/client/client.ts
|
|
6
396
|
var A2AClient = class _A2AClient {
|
|
397
|
+
static emptyOptions = void 0;
|
|
7
398
|
agentCardPromise;
|
|
8
|
-
requestIdCounter = 1;
|
|
9
|
-
serviceEndpointUrl;
|
|
10
|
-
// To be populated from AgentCard after fetching
|
|
11
399
|
customFetchImpl;
|
|
400
|
+
serviceEndpointUrl;
|
|
401
|
+
// To be populated from AgentCard after fetchin
|
|
402
|
+
// 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.
|
|
403
|
+
// New transport abstraction isn't going to expose individual transport specific fields, so to keep returning JSON-RPC IDs here for compatibility,
|
|
404
|
+
// keep counter here and pass it to JsonRpcTransport via an optional idOverride parameter (which is not visible via transport-agnostic A2ATransport interface).
|
|
405
|
+
transport;
|
|
406
|
+
requestIdCounter = 1;
|
|
12
407
|
/**
|
|
13
408
|
* Constructs an A2AClient instance from an AgentCard.
|
|
14
409
|
* @param agentCard The AgentCard object.
|
|
@@ -17,18 +412,22 @@ var A2AClient = class _A2AClient {
|
|
|
17
412
|
constructor(agentCard, options) {
|
|
18
413
|
this.customFetchImpl = options?.fetchImpl;
|
|
19
414
|
if (typeof agentCard === "string") {
|
|
20
|
-
console.warn(
|
|
415
|
+
console.warn(
|
|
416
|
+
"Warning: Constructing A2AClient with a URL is deprecated. Please use A2AClient.fromCardUrl() instead."
|
|
417
|
+
);
|
|
21
418
|
this.agentCardPromise = this._fetchAndCacheAgentCard(agentCard, options?.agentCardPath);
|
|
22
419
|
} else {
|
|
23
420
|
if (!agentCard.url) {
|
|
24
|
-
throw new Error(
|
|
421
|
+
throw new Error(
|
|
422
|
+
"Provided Agent Card does not contain a valid 'url' for the service endpoint."
|
|
423
|
+
);
|
|
25
424
|
}
|
|
26
425
|
this.serviceEndpointUrl = agentCard.url;
|
|
27
426
|
this.agentCardPromise = Promise.resolve(agentCard);
|
|
28
427
|
}
|
|
29
428
|
}
|
|
30
429
|
/**
|
|
31
|
-
* Dynamically resolves the fetch implementation to use for requests.
|
|
430
|
+
* Dynamically resolves the fetch implementation to use for requests.
|
|
32
431
|
* Prefers a custom implementation if provided, otherwise falls back to the global fetch.
|
|
33
432
|
* @returns The fetch implementation.
|
|
34
433
|
* @param args Arguments to pass to the fetch implementation.
|
|
@@ -54,7 +453,7 @@ var A2AClient = class _A2AClient {
|
|
|
54
453
|
static async fromCardUrl(agentCardUrl, options) {
|
|
55
454
|
const fetchImpl = options?.fetchImpl;
|
|
56
455
|
const requestInit = {
|
|
57
|
-
headers: {
|
|
456
|
+
headers: { Accept: "application/json" }
|
|
58
457
|
};
|
|
59
458
|
let response;
|
|
60
459
|
if (fetchImpl) {
|
|
@@ -67,76 +466,21 @@ var A2AClient = class _A2AClient {
|
|
|
67
466
|
);
|
|
68
467
|
}
|
|
69
468
|
if (!response.ok) {
|
|
70
|
-
throw new Error(
|
|
469
|
+
throw new Error(
|
|
470
|
+
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
|
471
|
+
);
|
|
71
472
|
}
|
|
72
473
|
let agentCard;
|
|
73
474
|
try {
|
|
74
475
|
agentCard = await response.json();
|
|
75
476
|
} catch (error) {
|
|
76
477
|
console.error("Failed to parse Agent Card JSON:", error);
|
|
77
|
-
throw new Error(
|
|
478
|
+
throw new Error(
|
|
479
|
+
`Failed to parse Agent Card JSON from ${agentCardUrl}. Original error: ${error.message}`
|
|
480
|
+
);
|
|
78
481
|
}
|
|
79
482
|
return new _A2AClient(agentCard, options);
|
|
80
483
|
}
|
|
81
|
-
/**
|
|
82
|
-
* Helper method to make a generic JSON-RPC POST request.
|
|
83
|
-
* @param method The RPC method name.
|
|
84
|
-
* @param params The parameters for the RPC method.
|
|
85
|
-
* @returns A Promise that resolves to the RPC response.
|
|
86
|
-
*/
|
|
87
|
-
async _postRpcRequest(method, params) {
|
|
88
|
-
const endpoint = await this._getServiceEndpoint();
|
|
89
|
-
const requestId = this.requestIdCounter++;
|
|
90
|
-
const rpcRequest = {
|
|
91
|
-
jsonrpc: "2.0",
|
|
92
|
-
method,
|
|
93
|
-
params,
|
|
94
|
-
// Cast because TParams structure varies per method
|
|
95
|
-
id: requestId
|
|
96
|
-
};
|
|
97
|
-
const httpResponse = await this._fetchRpc(endpoint, rpcRequest);
|
|
98
|
-
if (!httpResponse.ok) {
|
|
99
|
-
let errorBodyText = "(empty or non-JSON response)";
|
|
100
|
-
try {
|
|
101
|
-
errorBodyText = await httpResponse.text();
|
|
102
|
-
const errorJson = JSON.parse(errorBodyText);
|
|
103
|
-
if (errorJson.jsonrpc && errorJson.error) {
|
|
104
|
-
return errorJson;
|
|
105
|
-
} else if (!errorJson.jsonrpc && errorJson.error) {
|
|
106
|
-
throw new Error(`RPC error for ${method}: ${errorJson.error.message} (Code: ${errorJson.error.code}, HTTP Status: ${httpResponse.status}) Data: ${JSON.stringify(errorJson.error.data || {})}`);
|
|
107
|
-
} else if (!errorJson.jsonrpc) {
|
|
108
|
-
throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
|
|
109
|
-
}
|
|
110
|
-
} catch (e) {
|
|
111
|
-
if (e.message.startsWith("RPC error for") || e.message.startsWith("HTTP error for")) throw e;
|
|
112
|
-
throw new Error(`HTTP error for ${method}! Status: ${httpResponse.status} ${httpResponse.statusText}. Response: ${errorBodyText}`);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
const rpcResponse = await httpResponse.json();
|
|
116
|
-
if (rpcResponse.id !== requestId) {
|
|
117
|
-
console.error(`CRITICAL: RPC response ID mismatch for method ${method}. Expected ${requestId}, got ${rpcResponse.id}. This may lead to incorrect response handling.`);
|
|
118
|
-
}
|
|
119
|
-
return rpcResponse;
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* Internal helper method to fetch the RPC service endpoint.
|
|
123
|
-
* @param url The URL to fetch.
|
|
124
|
-
* @param rpcRequest The JSON-RPC request to send.
|
|
125
|
-
* @param acceptHeader The Accept header to use. Defaults to "application/json".
|
|
126
|
-
* @returns A Promise that resolves to the fetch HTTP response.
|
|
127
|
-
*/
|
|
128
|
-
async _fetchRpc(url, rpcRequest, acceptHeader = "application/json") {
|
|
129
|
-
const requestInit = {
|
|
130
|
-
method: "POST",
|
|
131
|
-
headers: {
|
|
132
|
-
"Content-Type": "application/json",
|
|
133
|
-
"Accept": acceptHeader
|
|
134
|
-
// Expect JSON response for non-streaming requests
|
|
135
|
-
},
|
|
136
|
-
body: JSON.stringify(rpcRequest)
|
|
137
|
-
};
|
|
138
|
-
return this._fetch(url, requestInit);
|
|
139
|
-
}
|
|
140
484
|
/**
|
|
141
485
|
* Sends a message to the agent.
|
|
142
486
|
* The behavior (blocking/non-blocking) and push notification configuration
|
|
@@ -146,7 +490,10 @@ var A2AClient = class _A2AClient {
|
|
|
146
490
|
* @returns A Promise resolving to SendMessageResponse, which can be a Message, Task, or an error.
|
|
147
491
|
*/
|
|
148
492
|
async sendMessage(params) {
|
|
149
|
-
return this.
|
|
493
|
+
return await this.invokeJsonRpc(
|
|
494
|
+
(t, p, id) => t.sendMessage(p, _A2AClient.emptyOptions, id),
|
|
495
|
+
params
|
|
496
|
+
);
|
|
150
497
|
}
|
|
151
498
|
/**
|
|
152
499
|
* Sends a message to the agent and streams back responses using Server-Sent Events (SSE).
|
|
@@ -160,36 +507,12 @@ var A2AClient = class _A2AClient {
|
|
|
160
507
|
async *sendMessageStream(params) {
|
|
161
508
|
const agentCard = await this.agentCardPromise;
|
|
162
509
|
if (!agentCard.capabilities?.streaming) {
|
|
163
|
-
throw new Error(
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
const clientRequestId = this.requestIdCounter++;
|
|
167
|
-
const rpcRequest = {
|
|
168
|
-
// This is the initial JSON-RPC request to establish the stream
|
|
169
|
-
jsonrpc: "2.0",
|
|
170
|
-
method: "message/stream",
|
|
171
|
-
params,
|
|
172
|
-
id: clientRequestId
|
|
173
|
-
};
|
|
174
|
-
const response = await this._fetchRpc(endpoint, rpcRequest, "text/event-stream");
|
|
175
|
-
if (!response.ok) {
|
|
176
|
-
let errorBody = "";
|
|
177
|
-
try {
|
|
178
|
-
errorBody = await response.text();
|
|
179
|
-
const errorJson = JSON.parse(errorBody);
|
|
180
|
-
if (errorJson.error) {
|
|
181
|
-
throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
|
|
182
|
-
}
|
|
183
|
-
} catch (e) {
|
|
184
|
-
if (e.message.startsWith("HTTP error establishing stream")) throw e;
|
|
185
|
-
throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}. Response: ${errorBody || "(empty)"}`);
|
|
186
|
-
}
|
|
187
|
-
throw new Error(`HTTP error establishing stream for message/stream: ${response.status} ${response.statusText}`);
|
|
188
|
-
}
|
|
189
|
-
if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
|
|
190
|
-
throw new Error("Invalid response Content-Type for SSE stream. Expected 'text/event-stream'.");
|
|
510
|
+
throw new Error(
|
|
511
|
+
"Agent does not support streaming (AgentCard.capabilities.streaming is not true)."
|
|
512
|
+
);
|
|
191
513
|
}
|
|
192
|
-
|
|
514
|
+
const transport = await this._getOrCreateTransport();
|
|
515
|
+
yield* transport.sendMessageStream(params);
|
|
193
516
|
}
|
|
194
517
|
/**
|
|
195
518
|
* Sets or updates the push notification configuration for a given task.
|
|
@@ -200,12 +523,11 @@ var A2AClient = class _A2AClient {
|
|
|
200
523
|
async setTaskPushNotificationConfig(params) {
|
|
201
524
|
const agentCard = await this.agentCardPromise;
|
|
202
525
|
if (!agentCard.capabilities?.pushNotifications) {
|
|
203
|
-
throw new Error(
|
|
526
|
+
throw new Error(
|
|
527
|
+
"Agent does not support push notifications (AgentCard.capabilities.pushNotifications is not true)."
|
|
528
|
+
);
|
|
204
529
|
}
|
|
205
|
-
return this.
|
|
206
|
-
"tasks/pushNotificationConfig/set",
|
|
207
|
-
params
|
|
208
|
-
);
|
|
530
|
+
return await this.invokeJsonRpc((t, p, id) => t.setTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id), params);
|
|
209
531
|
}
|
|
210
532
|
/**
|
|
211
533
|
* Gets the push notification configuration for a given task.
|
|
@@ -213,8 +535,8 @@ var A2AClient = class _A2AClient {
|
|
|
213
535
|
* @returns A Promise resolving to GetTaskPushNotificationConfigResponse.
|
|
214
536
|
*/
|
|
215
537
|
async getTaskPushNotificationConfig(params) {
|
|
216
|
-
return this.
|
|
217
|
-
|
|
538
|
+
return await this.invokeJsonRpc(
|
|
539
|
+
(t, p, id) => t.getTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id),
|
|
218
540
|
params
|
|
219
541
|
);
|
|
220
542
|
}
|
|
@@ -224,10 +546,7 @@ var A2AClient = class _A2AClient {
|
|
|
224
546
|
* @returns A Promise resolving to ListTaskPushNotificationConfigResponse.
|
|
225
547
|
*/
|
|
226
548
|
async listTaskPushNotificationConfig(params) {
|
|
227
|
-
return this.
|
|
228
|
-
"tasks/pushNotificationConfig/list",
|
|
229
|
-
params
|
|
230
|
-
);
|
|
549
|
+
return await this.invokeJsonRpc((t, p, id) => t.listTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id), params);
|
|
231
550
|
}
|
|
232
551
|
/**
|
|
233
552
|
* Deletes the push notification configuration for a given task.
|
|
@@ -235,10 +554,7 @@ var A2AClient = class _A2AClient {
|
|
|
235
554
|
* @returns A Promise resolving to DeleteTaskPushNotificationConfigResponse.
|
|
236
555
|
*/
|
|
237
556
|
async deleteTaskPushNotificationConfig(params) {
|
|
238
|
-
return this.
|
|
239
|
-
"tasks/pushNotificationConfig/delete",
|
|
240
|
-
params
|
|
241
|
-
);
|
|
557
|
+
return await this.invokeJsonRpc((t, p, id) => t.deleteTaskPushNotificationConfig(p, _A2AClient.emptyOptions, id), params);
|
|
242
558
|
}
|
|
243
559
|
/**
|
|
244
560
|
* Retrieves a task by its ID.
|
|
@@ -246,7 +562,10 @@ var A2AClient = class _A2AClient {
|
|
|
246
562
|
* @returns A Promise resolving to GetTaskResponse, which contains the Task object or an error.
|
|
247
563
|
*/
|
|
248
564
|
async getTask(params) {
|
|
249
|
-
return this.
|
|
565
|
+
return await this.invokeJsonRpc(
|
|
566
|
+
(t, p, id) => t.getTask(p, _A2AClient.emptyOptions, id),
|
|
567
|
+
params
|
|
568
|
+
);
|
|
250
569
|
}
|
|
251
570
|
/**
|
|
252
571
|
* Cancels a task by its ID.
|
|
@@ -254,18 +573,34 @@ var A2AClient = class _A2AClient {
|
|
|
254
573
|
* @returns A Promise resolving to CancelTaskResponse, which contains the updated Task object or an error.
|
|
255
574
|
*/
|
|
256
575
|
async cancelTask(params) {
|
|
257
|
-
return this.
|
|
576
|
+
return await this.invokeJsonRpc(
|
|
577
|
+
(t, p, id) => t.cancelTask(p, _A2AClient.emptyOptions, id),
|
|
578
|
+
params
|
|
579
|
+
);
|
|
258
580
|
}
|
|
259
581
|
/**
|
|
260
582
|
* @template TExtensionParams The type of parameters for the custom extension method.
|
|
261
|
-
* @template TExtensionResponse The type of response expected from the custom extension method.
|
|
583
|
+
* @template TExtensionResponse The type of response expected from the custom extension method.
|
|
262
584
|
* This should extend JSONRPCResponse. This ensures the extension response is still a valid A2A response.
|
|
263
585
|
* @param method Custom JSON-RPC method defined in the AgentCard's extensions.
|
|
264
586
|
* @param params Extension paramters defined in the AgentCard's extensions.
|
|
265
587
|
* @returns A Promise that resolves to the RPC response.
|
|
266
588
|
*/
|
|
267
589
|
async callExtensionMethod(method, params) {
|
|
268
|
-
|
|
590
|
+
const transport = await this._getOrCreateTransport();
|
|
591
|
+
try {
|
|
592
|
+
return await transport.callExtensionMethod(
|
|
593
|
+
method,
|
|
594
|
+
params,
|
|
595
|
+
this.requestIdCounter++
|
|
596
|
+
);
|
|
597
|
+
} catch (e) {
|
|
598
|
+
const errorResponse = extractJSONRPCError(e);
|
|
599
|
+
if (errorResponse) {
|
|
600
|
+
return errorResponse;
|
|
601
|
+
}
|
|
602
|
+
throw e;
|
|
603
|
+
}
|
|
269
604
|
}
|
|
270
605
|
/**
|
|
271
606
|
* Resubscribes to a task's event stream using Server-Sent Events (SSE).
|
|
@@ -279,129 +614,8 @@ var A2AClient = class _A2AClient {
|
|
|
279
614
|
if (!agentCard.capabilities?.streaming) {
|
|
280
615
|
throw new Error("Agent does not support streaming (required for tasks/resubscribe).");
|
|
281
616
|
}
|
|
282
|
-
const
|
|
283
|
-
|
|
284
|
-
const rpcRequest = {
|
|
285
|
-
// Initial JSON-RPC request to establish the stream
|
|
286
|
-
jsonrpc: "2.0",
|
|
287
|
-
method: "tasks/resubscribe",
|
|
288
|
-
params,
|
|
289
|
-
id: clientRequestId
|
|
290
|
-
};
|
|
291
|
-
const response = await this._fetch(endpoint, {
|
|
292
|
-
method: "POST",
|
|
293
|
-
headers: {
|
|
294
|
-
"Content-Type": "application/json",
|
|
295
|
-
"Accept": "text/event-stream"
|
|
296
|
-
},
|
|
297
|
-
body: JSON.stringify(rpcRequest)
|
|
298
|
-
});
|
|
299
|
-
if (!response.ok) {
|
|
300
|
-
let errorBody = "";
|
|
301
|
-
try {
|
|
302
|
-
errorBody = await response.text();
|
|
303
|
-
const errorJson = JSON.parse(errorBody);
|
|
304
|
-
if (errorJson.error) {
|
|
305
|
-
throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. RPC Error: ${errorJson.error.message} (Code: ${errorJson.error.code})`);
|
|
306
|
-
}
|
|
307
|
-
} catch (e) {
|
|
308
|
-
if (e.message.startsWith("HTTP error establishing stream")) throw e;
|
|
309
|
-
throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}. Response: ${errorBody || "(empty)"}`);
|
|
310
|
-
}
|
|
311
|
-
throw new Error(`HTTP error establishing stream for tasks/resubscribe: ${response.status} ${response.statusText}`);
|
|
312
|
-
}
|
|
313
|
-
if (!response.headers.get("Content-Type")?.startsWith("text/event-stream")) {
|
|
314
|
-
throw new Error("Invalid response Content-Type for SSE stream on resubscribe. Expected 'text/event-stream'.");
|
|
315
|
-
}
|
|
316
|
-
yield* this._parseA2ASseStream(response, clientRequestId);
|
|
317
|
-
}
|
|
318
|
-
/**
|
|
319
|
-
* Parses an HTTP response body as an A2A Server-Sent Event stream.
|
|
320
|
-
* Each 'data' field of an SSE event is expected to be a JSON-RPC 2.0 Response object,
|
|
321
|
-
* specifically a SendStreamingMessageResponse (or similar structure for resubscribe).
|
|
322
|
-
* @param response The HTTP Response object whose body is the SSE stream.
|
|
323
|
-
* @param originalRequestId The ID of the client's JSON-RPC request that initiated this stream.
|
|
324
|
-
* Used to validate the `id` in the streamed JSON-RPC responses.
|
|
325
|
-
* @returns An AsyncGenerator yielding the `result` field of each valid JSON-RPC success response from the stream.
|
|
326
|
-
*/
|
|
327
|
-
async *_parseA2ASseStream(response, originalRequestId) {
|
|
328
|
-
if (!response.body) {
|
|
329
|
-
throw new Error("SSE response body is undefined. Cannot read stream.");
|
|
330
|
-
}
|
|
331
|
-
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
332
|
-
let buffer = "";
|
|
333
|
-
let eventDataBuffer = "";
|
|
334
|
-
try {
|
|
335
|
-
while (true) {
|
|
336
|
-
const { done, value } = await reader.read();
|
|
337
|
-
if (done) {
|
|
338
|
-
if (eventDataBuffer.trim()) {
|
|
339
|
-
const result = this._processSseEventData(eventDataBuffer, originalRequestId);
|
|
340
|
-
yield result;
|
|
341
|
-
}
|
|
342
|
-
break;
|
|
343
|
-
}
|
|
344
|
-
buffer += value;
|
|
345
|
-
let lineEndIndex;
|
|
346
|
-
while ((lineEndIndex = buffer.indexOf("\n")) >= 0) {
|
|
347
|
-
const line = buffer.substring(0, lineEndIndex).trim();
|
|
348
|
-
buffer = buffer.substring(lineEndIndex + 1);
|
|
349
|
-
if (line === "") {
|
|
350
|
-
if (eventDataBuffer) {
|
|
351
|
-
const result = this._processSseEventData(eventDataBuffer, originalRequestId);
|
|
352
|
-
yield result;
|
|
353
|
-
eventDataBuffer = "";
|
|
354
|
-
}
|
|
355
|
-
} else if (line.startsWith("data:")) {
|
|
356
|
-
eventDataBuffer += line.substring(5).trimStart() + "\n";
|
|
357
|
-
} else if (line.startsWith(":")) {
|
|
358
|
-
} else if (line.includes(":")) {
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
} catch (error) {
|
|
363
|
-
console.error("Error reading or parsing SSE stream:", error.message);
|
|
364
|
-
throw error;
|
|
365
|
-
} finally {
|
|
366
|
-
reader.releaseLock();
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
/**
|
|
370
|
-
* Processes a single SSE event's data string, expecting it to be a JSON-RPC response.
|
|
371
|
-
* @param jsonData The string content from one or more 'data:' lines of an SSE event.
|
|
372
|
-
* @param originalRequestId The ID of the client's request that initiated the stream.
|
|
373
|
-
* @returns The `result` field of the parsed JSON-RPC success response.
|
|
374
|
-
* @throws Error if data is not valid JSON, not a valid JSON-RPC response, an error response, or ID mismatch.
|
|
375
|
-
*/
|
|
376
|
-
_processSseEventData(jsonData, originalRequestId) {
|
|
377
|
-
if (!jsonData.trim()) {
|
|
378
|
-
throw new Error("Attempted to process empty SSE event data.");
|
|
379
|
-
}
|
|
380
|
-
try {
|
|
381
|
-
const sseJsonRpcResponse = JSON.parse(jsonData.replace(/\n$/, ""));
|
|
382
|
-
const a2aStreamResponse = sseJsonRpcResponse;
|
|
383
|
-
if (a2aStreamResponse.id !== originalRequestId) {
|
|
384
|
-
console.warn(`SSE Event's JSON-RPC response ID mismatch. Client request ID: ${originalRequestId}, event response ID: ${a2aStreamResponse.id}.`);
|
|
385
|
-
}
|
|
386
|
-
if (this.isErrorResponse(a2aStreamResponse)) {
|
|
387
|
-
const err = a2aStreamResponse.error;
|
|
388
|
-
throw new Error(`SSE event contained an error: ${err.message} (Code: ${err.code}) Data: ${JSON.stringify(err.data || {})}`);
|
|
389
|
-
}
|
|
390
|
-
if (!("result" in a2aStreamResponse) || typeof a2aStreamResponse.result === "undefined") {
|
|
391
|
-
throw new Error(`SSE event JSON-RPC response is missing 'result' field. Data: ${jsonData}`);
|
|
392
|
-
}
|
|
393
|
-
const successResponse = a2aStreamResponse;
|
|
394
|
-
return successResponse.result;
|
|
395
|
-
} catch (e) {
|
|
396
|
-
if (e.message.startsWith("SSE event contained an error") || e.message.startsWith("SSE event JSON-RPC response is missing 'result' field")) {
|
|
397
|
-
throw e;
|
|
398
|
-
}
|
|
399
|
-
console.error("Failed to parse SSE event data string or unexpected JSON-RPC structure:", jsonData, e);
|
|
400
|
-
throw new Error(`Failed to parse SSE event data: "${jsonData.substring(0, 100)}...". Original error: ${e.message}`);
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
isErrorResponse(response) {
|
|
404
|
-
return "error" in response;
|
|
617
|
+
const transport = await this._getOrCreateTransport();
|
|
618
|
+
yield* transport.resubscribeTask(params);
|
|
405
619
|
}
|
|
406
620
|
////////////////////////////////////////////////////////////////////////////////
|
|
407
621
|
// Functions used to support old A2AClient Constructor to be deprecated soon
|
|
@@ -412,7 +626,16 @@ var A2AClient = class _A2AClient {
|
|
|
412
626
|
// * getAgentCard changed to this.agentCard
|
|
413
627
|
// * delete resolveAgentCardUrl(), _fetchAndCacheAgentCard(),
|
|
414
628
|
// agentCardPath from A2AClientOptions
|
|
629
|
+
// * delete _getOrCreateTransport
|
|
415
630
|
////////////////////////////////////////////////////////////////////////////////
|
|
631
|
+
async _getOrCreateTransport() {
|
|
632
|
+
if (this.transport) {
|
|
633
|
+
return this.transport;
|
|
634
|
+
}
|
|
635
|
+
const endpoint = await this._getServiceEndpoint();
|
|
636
|
+
this.transport = new JsonRpcTransport({ fetchImpl: this.customFetchImpl, endpoint });
|
|
637
|
+
return this.transport;
|
|
638
|
+
}
|
|
416
639
|
/**
|
|
417
640
|
* Fetches the Agent Card from the agent's well-known URI and caches its service endpoint URL.
|
|
418
641
|
* This method is called by the constructor.
|
|
@@ -424,14 +647,18 @@ var A2AClient = class _A2AClient {
|
|
|
424
647
|
try {
|
|
425
648
|
const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
|
|
426
649
|
const response = await this._fetch(agentCardUrl, {
|
|
427
|
-
headers: {
|
|
650
|
+
headers: { Accept: "application/json" }
|
|
428
651
|
});
|
|
429
652
|
if (!response.ok) {
|
|
430
|
-
throw new Error(
|
|
653
|
+
throw new Error(
|
|
654
|
+
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
|
655
|
+
);
|
|
431
656
|
}
|
|
432
657
|
const agentCard = await response.json();
|
|
433
658
|
if (!agentCard.url) {
|
|
434
|
-
throw new Error(
|
|
659
|
+
throw new Error(
|
|
660
|
+
"Fetched Agent Card does not contain a valid 'url' for the service endpoint."
|
|
661
|
+
);
|
|
435
662
|
}
|
|
436
663
|
this.serviceEndpointUrl = agentCard.url;
|
|
437
664
|
return agentCard;
|
|
@@ -441,22 +668,24 @@ var A2AClient = class _A2AClient {
|
|
|
441
668
|
}
|
|
442
669
|
}
|
|
443
670
|
/**
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
671
|
+
* Retrieves the Agent Card.
|
|
672
|
+
* If an `agentBaseUrl` is provided, it fetches the card from that specific URL.
|
|
673
|
+
* Otherwise, it returns the card fetched and cached during client construction.
|
|
674
|
+
* @param agentBaseUrl Optional. The base URL of the agent to fetch the card from.
|
|
675
|
+
* @param agentCardPath path to the agent card, defaults to .well-known/agent-card.json
|
|
676
|
+
* If provided, this will fetch a new card, not use the cached one from the constructor's URL.
|
|
677
|
+
* @returns A Promise that resolves to the AgentCard.
|
|
678
|
+
*/
|
|
452
679
|
async getAgentCard(agentBaseUrl, agentCardPath) {
|
|
453
680
|
if (agentBaseUrl) {
|
|
454
681
|
const agentCardUrl = this.resolveAgentCardUrl(agentBaseUrl, agentCardPath);
|
|
455
682
|
const response = await this._fetch(agentCardUrl, {
|
|
456
|
-
headers: {
|
|
683
|
+
headers: { Accept: "application/json" }
|
|
457
684
|
});
|
|
458
685
|
if (!response.ok) {
|
|
459
|
-
throw new Error(
|
|
686
|
+
throw new Error(
|
|
687
|
+
`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status} ${response.statusText}`
|
|
688
|
+
);
|
|
460
689
|
}
|
|
461
690
|
return await response.json();
|
|
462
691
|
}
|
|
@@ -480,11 +709,39 @@ var A2AClient = class _A2AClient {
|
|
|
480
709
|
}
|
|
481
710
|
await this.agentCardPromise;
|
|
482
711
|
if (!this.serviceEndpointUrl) {
|
|
483
|
-
throw new Error(
|
|
712
|
+
throw new Error(
|
|
713
|
+
"Agent Card URL for RPC endpoint is not available. Fetching might have failed."
|
|
714
|
+
);
|
|
484
715
|
}
|
|
485
716
|
return this.serviceEndpointUrl;
|
|
486
717
|
}
|
|
718
|
+
async invokeJsonRpc(caller, params) {
|
|
719
|
+
const transport = await this._getOrCreateTransport();
|
|
720
|
+
const requestId = this.requestIdCounter++;
|
|
721
|
+
try {
|
|
722
|
+
const result = await caller(transport, params, requestId);
|
|
723
|
+
return {
|
|
724
|
+
id: requestId,
|
|
725
|
+
jsonrpc: "2.0",
|
|
726
|
+
result: result ?? null
|
|
727
|
+
// JSON-RPC requires result property on success, it will be null for "void" methods.
|
|
728
|
+
};
|
|
729
|
+
} catch (e) {
|
|
730
|
+
const errorResponse = extractJSONRPCError(e);
|
|
731
|
+
if (errorResponse) {
|
|
732
|
+
return errorResponse;
|
|
733
|
+
}
|
|
734
|
+
throw e;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
487
737
|
};
|
|
738
|
+
function extractJSONRPCError(error) {
|
|
739
|
+
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) {
|
|
740
|
+
return error.errorResponse;
|
|
741
|
+
} else {
|
|
742
|
+
return void 0;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
488
745
|
|
|
489
746
|
// src/client/auth-handler.ts
|
|
490
747
|
function createAuthenticatingFetchWithRetry(fetchImpl, authHandler) {
|
|
@@ -518,7 +775,508 @@ function createAuthenticatingFetchWithRetry(fetchImpl, authHandler) {
|
|
|
518
775
|
Object.defineProperties(authFetch, Object.getOwnPropertyDescriptors(fetchImpl));
|
|
519
776
|
return authFetch;
|
|
520
777
|
}
|
|
778
|
+
|
|
779
|
+
// src/client/card-resolver.ts
|
|
780
|
+
var DefaultAgentCardResolver = class {
|
|
781
|
+
constructor(options) {
|
|
782
|
+
this.options = options;
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Fetches the agent card based on provided base URL and path.
|
|
786
|
+
* Path is selected in the following order:
|
|
787
|
+
* 1) path parameter
|
|
788
|
+
* 2) path from options
|
|
789
|
+
* 3) .well-known/agent-card.json
|
|
790
|
+
*/
|
|
791
|
+
async resolve(baseUrl, path) {
|
|
792
|
+
const agentCardUrl = new URL(path ?? this.options?.path ?? AGENT_CARD_PATH, baseUrl);
|
|
793
|
+
const response = await this.fetchImpl(agentCardUrl);
|
|
794
|
+
if (!response.ok) {
|
|
795
|
+
throw new Error(`Failed to fetch Agent Card from ${agentCardUrl}: ${response.status}`);
|
|
796
|
+
}
|
|
797
|
+
return await response.json();
|
|
798
|
+
}
|
|
799
|
+
fetchImpl(...args) {
|
|
800
|
+
if (this.options?.fetchImpl) {
|
|
801
|
+
return this.options.fetchImpl(...args);
|
|
802
|
+
}
|
|
803
|
+
return fetch(...args);
|
|
804
|
+
}
|
|
805
|
+
};
|
|
806
|
+
var AgentCardResolver = {
|
|
807
|
+
default: new DefaultAgentCardResolver()
|
|
808
|
+
};
|
|
809
|
+
|
|
810
|
+
// src/client/multitransport-client.ts
|
|
811
|
+
var Client = class {
|
|
812
|
+
constructor(transport, agentCard, config) {
|
|
813
|
+
this.transport = transport;
|
|
814
|
+
this.agentCard = agentCard;
|
|
815
|
+
this.config = config;
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* If the current agent card supports the extended feature, it will try to fetch the extended agent card from the server,
|
|
819
|
+
* Otherwise it will return the current agent card value.
|
|
820
|
+
*/
|
|
821
|
+
async getAgentCard(options) {
|
|
822
|
+
if (this.agentCard.supportsAuthenticatedExtendedCard) {
|
|
823
|
+
this.agentCard = await this.executeWithInterceptors(
|
|
824
|
+
{ method: "getAgentCard" },
|
|
825
|
+
options,
|
|
826
|
+
(_, options2) => this.transport.getExtendedAgentCard(options2)
|
|
827
|
+
);
|
|
828
|
+
}
|
|
829
|
+
return this.agentCard;
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* Sends a message to an agent to initiate a new interaction or to continue an existing one.
|
|
833
|
+
* Uses blocking mode by default.
|
|
834
|
+
*/
|
|
835
|
+
sendMessage(params, options) {
|
|
836
|
+
params = this.applyClientConfig({
|
|
837
|
+
params,
|
|
838
|
+
blocking: !(this.config?.polling ?? false)
|
|
839
|
+
});
|
|
840
|
+
return this.executeWithInterceptors(
|
|
841
|
+
{ method: "sendMessage", value: params },
|
|
842
|
+
options,
|
|
843
|
+
this.transport.sendMessage.bind(this.transport)
|
|
844
|
+
);
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Sends a message to an agent to initiate/continue a task AND subscribes the client to real-time updates for that task.
|
|
848
|
+
* Performs fallback to non-streaming if not supported by the agent.
|
|
849
|
+
*/
|
|
850
|
+
async *sendMessageStream(params, options) {
|
|
851
|
+
const method = "sendMessageStream";
|
|
852
|
+
params = this.applyClientConfig({ params, blocking: true });
|
|
853
|
+
const beforeArgs = {
|
|
854
|
+
input: { method, value: params },
|
|
855
|
+
agentCard: this.agentCard,
|
|
856
|
+
options
|
|
857
|
+
};
|
|
858
|
+
const beforeResult = await this.interceptBefore(beforeArgs);
|
|
859
|
+
if (beforeResult) {
|
|
860
|
+
const earlyReturn = beforeResult.earlyReturn.value;
|
|
861
|
+
const afterArgs = {
|
|
862
|
+
result: { method, value: earlyReturn },
|
|
863
|
+
agentCard: this.agentCard,
|
|
864
|
+
options: beforeArgs.options
|
|
865
|
+
};
|
|
866
|
+
await this.interceptAfter(afterArgs, beforeResult.executed);
|
|
867
|
+
yield afterArgs.result.value;
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
if (!this.agentCard.capabilities.streaming) {
|
|
871
|
+
const result = await this.transport.sendMessage(beforeArgs.input.value, beforeArgs.options);
|
|
872
|
+
const afterArgs = {
|
|
873
|
+
result: { method, value: result },
|
|
874
|
+
agentCard: this.agentCard,
|
|
875
|
+
options: beforeArgs.options
|
|
876
|
+
};
|
|
877
|
+
await this.interceptAfter(afterArgs);
|
|
878
|
+
yield afterArgs.result.value;
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
for await (const event of this.transport.sendMessageStream(
|
|
882
|
+
beforeArgs.input.value,
|
|
883
|
+
beforeArgs.options
|
|
884
|
+
)) {
|
|
885
|
+
const afterArgs = {
|
|
886
|
+
result: { method, value: event },
|
|
887
|
+
agentCard: this.agentCard,
|
|
888
|
+
options: beforeArgs.options
|
|
889
|
+
};
|
|
890
|
+
await this.interceptAfter(afterArgs);
|
|
891
|
+
yield afterArgs.result.value;
|
|
892
|
+
if (afterArgs.earlyReturn) {
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Sets or updates the push notification configuration for a specified task.
|
|
899
|
+
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
|
900
|
+
*/
|
|
901
|
+
setTaskPushNotificationConfig(params, options) {
|
|
902
|
+
if (!this.agentCard.capabilities.pushNotifications) {
|
|
903
|
+
throw new PushNotificationNotSupportedError();
|
|
904
|
+
}
|
|
905
|
+
return this.executeWithInterceptors(
|
|
906
|
+
{ method: "setTaskPushNotificationConfig", value: params },
|
|
907
|
+
options,
|
|
908
|
+
this.transport.setTaskPushNotificationConfig.bind(this.transport)
|
|
909
|
+
);
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Retrieves the current push notification configuration for a specified task.
|
|
913
|
+
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
|
914
|
+
*/
|
|
915
|
+
getTaskPushNotificationConfig(params, options) {
|
|
916
|
+
if (!this.agentCard.capabilities.pushNotifications) {
|
|
917
|
+
throw new PushNotificationNotSupportedError();
|
|
918
|
+
}
|
|
919
|
+
return this.executeWithInterceptors(
|
|
920
|
+
{ method: "getTaskPushNotificationConfig", value: params },
|
|
921
|
+
options,
|
|
922
|
+
this.transport.getTaskPushNotificationConfig.bind(this.transport)
|
|
923
|
+
);
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* Retrieves the associated push notification configurations for a specified task.
|
|
927
|
+
* Requires the server to have AgentCard.capabilities.pushNotifications: true.
|
|
928
|
+
*/
|
|
929
|
+
listTaskPushNotificationConfig(params, options) {
|
|
930
|
+
if (!this.agentCard.capabilities.pushNotifications) {
|
|
931
|
+
throw new PushNotificationNotSupportedError();
|
|
932
|
+
}
|
|
933
|
+
return this.executeWithInterceptors(
|
|
934
|
+
{ method: "listTaskPushNotificationConfig", value: params },
|
|
935
|
+
options,
|
|
936
|
+
this.transport.listTaskPushNotificationConfig.bind(this.transport)
|
|
937
|
+
);
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* Deletes an associated push notification configuration for a task.
|
|
941
|
+
*/
|
|
942
|
+
deleteTaskPushNotificationConfig(params, options) {
|
|
943
|
+
return this.executeWithInterceptors(
|
|
944
|
+
{ method: "deleteTaskPushNotificationConfig", value: params },
|
|
945
|
+
options,
|
|
946
|
+
this.transport.deleteTaskPushNotificationConfig.bind(this.transport)
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* Retrieves the current state (including status, artifacts, and optionally history) of a previously initiated task.
|
|
951
|
+
*/
|
|
952
|
+
getTask(params, options) {
|
|
953
|
+
return this.executeWithInterceptors(
|
|
954
|
+
{ method: "getTask", value: params },
|
|
955
|
+
options,
|
|
956
|
+
this.transport.getTask.bind(this.transport)
|
|
957
|
+
);
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Requests the cancellation of an ongoing task. The server will attempt to cancel the task,
|
|
961
|
+
* 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).
|
|
962
|
+
*/
|
|
963
|
+
cancelTask(params, options) {
|
|
964
|
+
return this.executeWithInterceptors(
|
|
965
|
+
{ method: "cancelTask", value: params },
|
|
966
|
+
options,
|
|
967
|
+
this.transport.cancelTask.bind(this.transport)
|
|
968
|
+
);
|
|
969
|
+
}
|
|
970
|
+
/**
|
|
971
|
+
* Allows a client to reconnect to an updates stream for an ongoing task after a previous connection was interrupted.
|
|
972
|
+
*/
|
|
973
|
+
async *resubscribeTask(params, options) {
|
|
974
|
+
const method = "resubscribeTask";
|
|
975
|
+
const beforeArgs = {
|
|
976
|
+
input: { method, value: params },
|
|
977
|
+
agentCard: this.agentCard,
|
|
978
|
+
options
|
|
979
|
+
};
|
|
980
|
+
const beforeResult = await this.interceptBefore(beforeArgs);
|
|
981
|
+
if (beforeResult) {
|
|
982
|
+
const earlyReturn = beforeResult.earlyReturn.value;
|
|
983
|
+
const afterArgs = {
|
|
984
|
+
result: { method, value: earlyReturn },
|
|
985
|
+
agentCard: this.agentCard,
|
|
986
|
+
options: beforeArgs.options
|
|
987
|
+
};
|
|
988
|
+
await this.interceptAfter(afterArgs, beforeResult.executed);
|
|
989
|
+
yield afterArgs.result.value;
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
992
|
+
for await (const event of this.transport.resubscribeTask(
|
|
993
|
+
beforeArgs.input.value,
|
|
994
|
+
beforeArgs.options
|
|
995
|
+
)) {
|
|
996
|
+
const afterArgs = {
|
|
997
|
+
result: { method, value: event },
|
|
998
|
+
agentCard: this.agentCard,
|
|
999
|
+
options: beforeArgs.options
|
|
1000
|
+
};
|
|
1001
|
+
await this.interceptAfter(afterArgs);
|
|
1002
|
+
yield afterArgs.result.value;
|
|
1003
|
+
if (afterArgs.earlyReturn) {
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
applyClientConfig({
|
|
1009
|
+
params,
|
|
1010
|
+
blocking
|
|
1011
|
+
}) {
|
|
1012
|
+
const result = { ...params, configuration: params.configuration ?? {} };
|
|
1013
|
+
if (!result.configuration.acceptedOutputModes && this.config?.acceptedOutputModes) {
|
|
1014
|
+
result.configuration.acceptedOutputModes = this.config.acceptedOutputModes;
|
|
1015
|
+
}
|
|
1016
|
+
if (!result.configuration.pushNotificationConfig && this.config?.pushNotificationConfig) {
|
|
1017
|
+
result.configuration.pushNotificationConfig = this.config.pushNotificationConfig;
|
|
1018
|
+
}
|
|
1019
|
+
result.configuration.blocking ??= blocking;
|
|
1020
|
+
return result;
|
|
1021
|
+
}
|
|
1022
|
+
async executeWithInterceptors(input, options, transportCall) {
|
|
1023
|
+
const beforeArgs = {
|
|
1024
|
+
input,
|
|
1025
|
+
agentCard: this.agentCard,
|
|
1026
|
+
options
|
|
1027
|
+
};
|
|
1028
|
+
const beforeResult = await this.interceptBefore(beforeArgs);
|
|
1029
|
+
if (beforeResult) {
|
|
1030
|
+
const afterArgs2 = {
|
|
1031
|
+
result: {
|
|
1032
|
+
method: input.method,
|
|
1033
|
+
value: beforeResult.earlyReturn.value
|
|
1034
|
+
},
|
|
1035
|
+
agentCard: this.agentCard,
|
|
1036
|
+
options: beforeArgs.options
|
|
1037
|
+
};
|
|
1038
|
+
await this.interceptAfter(afterArgs2, beforeResult.executed);
|
|
1039
|
+
return afterArgs2.result.value;
|
|
1040
|
+
}
|
|
1041
|
+
const result = await transportCall(beforeArgs.input.value, beforeArgs.options);
|
|
1042
|
+
const afterArgs = {
|
|
1043
|
+
result: { method: input.method, value: result },
|
|
1044
|
+
agentCard: this.agentCard,
|
|
1045
|
+
options: beforeArgs.options
|
|
1046
|
+
};
|
|
1047
|
+
await this.interceptAfter(afterArgs);
|
|
1048
|
+
return afterArgs.result.value;
|
|
1049
|
+
}
|
|
1050
|
+
async interceptBefore(args) {
|
|
1051
|
+
if (!this.config?.interceptors || this.config.interceptors.length === 0) {
|
|
1052
|
+
return;
|
|
1053
|
+
}
|
|
1054
|
+
const executed = [];
|
|
1055
|
+
for (const interceptor of this.config.interceptors) {
|
|
1056
|
+
await interceptor.before(args);
|
|
1057
|
+
executed.push(interceptor);
|
|
1058
|
+
if (args.earlyReturn) {
|
|
1059
|
+
return {
|
|
1060
|
+
earlyReturn: args.earlyReturn,
|
|
1061
|
+
executed
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
async interceptAfter(args, interceptors) {
|
|
1067
|
+
const reversedInterceptors = [...interceptors ?? this.config?.interceptors ?? []].reverse();
|
|
1068
|
+
for (const interceptor of reversedInterceptors) {
|
|
1069
|
+
await interceptor.after(args);
|
|
1070
|
+
if (args.earlyReturn) {
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
|
|
1077
|
+
// src/client/factory.ts
|
|
1078
|
+
var ClientFactoryOptions = {
|
|
1079
|
+
/**
|
|
1080
|
+
* SDK default options for {@link ClientFactory}.
|
|
1081
|
+
*/
|
|
1082
|
+
default: {
|
|
1083
|
+
transports: [new JsonRpcTransportFactory()]
|
|
1084
|
+
},
|
|
1085
|
+
/**
|
|
1086
|
+
* Creates new options by merging an original and an override object.
|
|
1087
|
+
* Transports are merged based on `TransportFactory.protocolName`,
|
|
1088
|
+
* interceptors are concatenated, other fields are overriden.
|
|
1089
|
+
*
|
|
1090
|
+
* @example
|
|
1091
|
+
* ```ts
|
|
1092
|
+
* const options = ClientFactoryOptions.createFrom(ClientFactoryOptions.default, {
|
|
1093
|
+
* transports: [new MyCustomTransportFactory()], // adds a custom transport
|
|
1094
|
+
* clientConfig: { interceptors: [new MyInterceptor()] }, // adds a custom interceptor
|
|
1095
|
+
* });
|
|
1096
|
+
* ```
|
|
1097
|
+
*/
|
|
1098
|
+
createFrom(original, overrides) {
|
|
1099
|
+
return {
|
|
1100
|
+
...original,
|
|
1101
|
+
...overrides,
|
|
1102
|
+
transports: mergeTransports(original.transports, overrides.transports),
|
|
1103
|
+
clientConfig: {
|
|
1104
|
+
...original.clientConfig ?? {},
|
|
1105
|
+
...overrides.clientConfig ?? {},
|
|
1106
|
+
interceptors: mergeArrays(
|
|
1107
|
+
original.clientConfig?.interceptors,
|
|
1108
|
+
overrides.clientConfig?.interceptors
|
|
1109
|
+
),
|
|
1110
|
+
acceptedOutputModes: overrides.clientConfig?.acceptedOutputModes ?? original.clientConfig?.acceptedOutputModes
|
|
1111
|
+
},
|
|
1112
|
+
preferredTransports: overrides.preferredTransports ?? original.preferredTransports
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
};
|
|
1116
|
+
var ClientFactory = class {
|
|
1117
|
+
constructor(options = ClientFactoryOptions.default) {
|
|
1118
|
+
this.options = options;
|
|
1119
|
+
if (!options.transports || options.transports.length === 0) {
|
|
1120
|
+
throw new Error("No transports provided");
|
|
1121
|
+
}
|
|
1122
|
+
this.transportsByName = transportsByName(options.transports);
|
|
1123
|
+
for (const transport of options.preferredTransports ?? []) {
|
|
1124
|
+
const factory = this.options.transports.find((t) => t.protocolName === transport);
|
|
1125
|
+
if (!factory) {
|
|
1126
|
+
throw new Error(
|
|
1127
|
+
`Unknown preferred transport: ${transport}, available transports: ${[...this.transportsByName.keys()].join()}`
|
|
1128
|
+
);
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
this.agentCardResolver = options.cardResolver ?? AgentCardResolver.default;
|
|
1132
|
+
}
|
|
1133
|
+
transportsByName;
|
|
1134
|
+
agentCardResolver;
|
|
1135
|
+
/**
|
|
1136
|
+
* Creates a new client from the provided agent card.
|
|
1137
|
+
*/
|
|
1138
|
+
async createFromAgentCard(agentCard) {
|
|
1139
|
+
const agentCardPreferred = agentCard.preferredTransport ?? JsonRpcTransportFactory.name;
|
|
1140
|
+
const additionalInterfaces = agentCard.additionalInterfaces ?? [];
|
|
1141
|
+
const urlsPerAgentTransports = new Map([
|
|
1142
|
+
[agentCardPreferred, agentCard.url],
|
|
1143
|
+
...additionalInterfaces.map((i) => [i.transport, i.url])
|
|
1144
|
+
]);
|
|
1145
|
+
const transportsByPreference = [
|
|
1146
|
+
...this.options.preferredTransports ?? [],
|
|
1147
|
+
agentCardPreferred,
|
|
1148
|
+
...additionalInterfaces.map((i) => i.transport)
|
|
1149
|
+
];
|
|
1150
|
+
for (const transport of transportsByPreference) {
|
|
1151
|
+
if (!urlsPerAgentTransports.has(transport)) {
|
|
1152
|
+
continue;
|
|
1153
|
+
}
|
|
1154
|
+
const factory = this.transportsByName.get(transport);
|
|
1155
|
+
if (!factory) {
|
|
1156
|
+
continue;
|
|
1157
|
+
}
|
|
1158
|
+
return new Client(
|
|
1159
|
+
await factory.create(urlsPerAgentTransports.get(transport), agentCard),
|
|
1160
|
+
agentCard,
|
|
1161
|
+
this.options.clientConfig
|
|
1162
|
+
);
|
|
1163
|
+
}
|
|
1164
|
+
throw new Error(
|
|
1165
|
+
"No compatible transport found, available transports: " + [...this.transportsByName.keys()].join()
|
|
1166
|
+
);
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Downloads agent card using AgentCardResolver from options
|
|
1170
|
+
* and creates a new client from the downloaded card.
|
|
1171
|
+
*
|
|
1172
|
+
* @example
|
|
1173
|
+
* ```ts
|
|
1174
|
+
* const factory = new ClientFactory(); // use default options and default {@link AgentCardResolver}.
|
|
1175
|
+
* const client1 = await factory.createFromUrl('https://example.com'); // /.well-known/agent-card.json is used by default
|
|
1176
|
+
* const client2 = await factory.createFromUrl('https://example.com', '/my-agent-card.json'); // specify custom path
|
|
1177
|
+
* const client3 = await factory.createFromUrl('https://example.com/my-agent-card.json', ''); // specify full URL and set path to empty
|
|
1178
|
+
* ```
|
|
1179
|
+
*/
|
|
1180
|
+
async createFromUrl(baseUrl, path) {
|
|
1181
|
+
const agentCard = await this.agentCardResolver.resolve(baseUrl, path);
|
|
1182
|
+
return this.createFromAgentCard(agentCard);
|
|
1183
|
+
}
|
|
1184
|
+
};
|
|
1185
|
+
function mergeTransports(original, overrides) {
|
|
1186
|
+
if (!overrides) {
|
|
1187
|
+
return original;
|
|
1188
|
+
}
|
|
1189
|
+
const result = transportsByName(original);
|
|
1190
|
+
const overridesByName = transportsByName(overrides);
|
|
1191
|
+
for (const [name, factory] of overridesByName) {
|
|
1192
|
+
result.set(name, factory);
|
|
1193
|
+
}
|
|
1194
|
+
return Array.from(result.values());
|
|
1195
|
+
}
|
|
1196
|
+
function transportsByName(transports) {
|
|
1197
|
+
const result = /* @__PURE__ */ new Map();
|
|
1198
|
+
if (!transports) {
|
|
1199
|
+
return result;
|
|
1200
|
+
}
|
|
1201
|
+
for (const t of transports) {
|
|
1202
|
+
if (result.has(t.protocolName)) {
|
|
1203
|
+
throw new Error(`Duplicate protocol name: ${t.protocolName}`);
|
|
1204
|
+
}
|
|
1205
|
+
result.set(t.protocolName, t);
|
|
1206
|
+
}
|
|
1207
|
+
return result;
|
|
1208
|
+
}
|
|
1209
|
+
function mergeArrays(a1, a2) {
|
|
1210
|
+
if (!a1 && !a2) {
|
|
1211
|
+
return void 0;
|
|
1212
|
+
}
|
|
1213
|
+
return [...a1 ?? [], ...a2 ?? []];
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
// src/client/service-parameters.ts
|
|
1217
|
+
var ServiceParameters = {
|
|
1218
|
+
create(...updates) {
|
|
1219
|
+
return ServiceParameters.createFrom(void 0, ...updates);
|
|
1220
|
+
},
|
|
1221
|
+
createFrom: (serviceParameters, ...updates) => {
|
|
1222
|
+
const result = serviceParameters ? { ...serviceParameters } : {};
|
|
1223
|
+
for (const update of updates) {
|
|
1224
|
+
update(result);
|
|
1225
|
+
}
|
|
1226
|
+
return result;
|
|
1227
|
+
}
|
|
1228
|
+
};
|
|
1229
|
+
function withA2AExtensions(...extensions) {
|
|
1230
|
+
return (parameters) => {
|
|
1231
|
+
parameters[HTTP_EXTENSION_HEADER] = Extensions.toServiceParameter(extensions);
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
// src/client/context.ts
|
|
1236
|
+
var ClientCallContext = {
|
|
1237
|
+
/**
|
|
1238
|
+
* Create a new {@link ClientCallContext} with optional updates applied.
|
|
1239
|
+
*/
|
|
1240
|
+
create: (...updates) => {
|
|
1241
|
+
return ClientCallContext.createFrom(void 0, ...updates);
|
|
1242
|
+
},
|
|
1243
|
+
/**
|
|
1244
|
+
* Create a new {@link ClientCallContext} based on an existing one with updates applied.
|
|
1245
|
+
*/
|
|
1246
|
+
createFrom: (context, ...updates) => {
|
|
1247
|
+
const result = context ? { ...context } : {};
|
|
1248
|
+
for (const update of updates) {
|
|
1249
|
+
update(result);
|
|
1250
|
+
}
|
|
1251
|
+
return result;
|
|
1252
|
+
}
|
|
1253
|
+
};
|
|
1254
|
+
var ClientCallContextKey = class {
|
|
1255
|
+
symbol;
|
|
1256
|
+
constructor(description) {
|
|
1257
|
+
this.symbol = Symbol(description);
|
|
1258
|
+
}
|
|
1259
|
+
set(value) {
|
|
1260
|
+
return (context) => {
|
|
1261
|
+
context[this.symbol] = value;
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
get(context) {
|
|
1265
|
+
return context[this.symbol];
|
|
1266
|
+
}
|
|
1267
|
+
};
|
|
521
1268
|
export {
|
|
522
1269
|
A2AClient,
|
|
523
|
-
|
|
1270
|
+
AgentCardResolver,
|
|
1271
|
+
Client,
|
|
1272
|
+
ClientCallContext,
|
|
1273
|
+
ClientCallContextKey,
|
|
1274
|
+
ClientFactory,
|
|
1275
|
+
ClientFactoryOptions,
|
|
1276
|
+
DefaultAgentCardResolver,
|
|
1277
|
+
JsonRpcTransport,
|
|
1278
|
+
JsonRpcTransportFactory,
|
|
1279
|
+
ServiceParameters,
|
|
1280
|
+
createAuthenticatingFetchWithRetry,
|
|
1281
|
+
withA2AExtensions
|
|
524
1282
|
};
|