@a2a-js/sdk 0.3.5 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,49 @@
1
+ import { E as Extensions, ae as AgentCard, x as MessageSendParams, F as Message, ay as Task, aQ as TaskStatusUpdateEvent, aS as TaskArtifactUpdateEvent, X as TaskQueryParams, Z as TaskIdParams, $ as TaskPushNotificationConfig, a3 as GetTaskPushNotificationConfigParams, a7 as ListTaskPushNotificationConfigParams, a9 as DeleteTaskPushNotificationConfigParams } from './extensions-DvruCIzw.cjs';
2
+
3
+ /**
4
+ * Represents a user accessing A2A server.
5
+ */
6
+ interface User {
7
+ /**
8
+ * Indicates whether the user is authenticated.
9
+ */
10
+ get isAuthenticated(): boolean;
11
+ /**
12
+ * A unique name (identifier) for the user.
13
+ */
14
+ get userName(): string;
15
+ }
16
+ /**
17
+ * An implementation of {@link User} representing an unauthenticated user.
18
+ */
19
+ declare class UnauthenticatedUser implements User {
20
+ get isAuthenticated(): boolean;
21
+ get userName(): string;
22
+ }
23
+
24
+ declare class ServerCallContext {
25
+ private readonly _requestedExtensions?;
26
+ private readonly _user?;
27
+ private _activatedExtensions?;
28
+ constructor(requestedExtensions?: Extensions, user?: User);
29
+ get user(): User | undefined;
30
+ get activatedExtensions(): Extensions | undefined;
31
+ get requestedExtensions(): Extensions | undefined;
32
+ addActivatedExtension(uri: string): void;
33
+ }
34
+
35
+ interface A2ARequestHandler {
36
+ getAgentCard(): Promise<AgentCard>;
37
+ getAuthenticatedExtendedAgentCard(context?: ServerCallContext): Promise<AgentCard>;
38
+ sendMessage(params: MessageSendParams, context?: ServerCallContext): Promise<Message | Task>;
39
+ sendMessageStream(params: MessageSendParams, context?: ServerCallContext): AsyncGenerator<Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent, void, undefined>;
40
+ getTask(params: TaskQueryParams, context?: ServerCallContext): Promise<Task>;
41
+ cancelTask(params: TaskIdParams, context?: ServerCallContext): Promise<Task>;
42
+ setTaskPushNotificationConfig(params: TaskPushNotificationConfig, context?: ServerCallContext): Promise<TaskPushNotificationConfig>;
43
+ getTaskPushNotificationConfig(params: TaskIdParams | GetTaskPushNotificationConfigParams, context?: ServerCallContext): Promise<TaskPushNotificationConfig>;
44
+ listTaskPushNotificationConfigs(params: ListTaskPushNotificationConfigParams, context?: ServerCallContext): Promise<TaskPushNotificationConfig[]>;
45
+ deleteTaskPushNotificationConfig(params: DeleteTaskPushNotificationConfigParams, context?: ServerCallContext): Promise<void>;
46
+ resubscribe(params: TaskIdParams, context?: ServerCallContext): AsyncGenerator<Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent, void, undefined>;
47
+ }
48
+
49
+ export { type A2ARequestHandler as A, ServerCallContext as S, type User as U, UnauthenticatedUser as a };
@@ -0,0 +1,49 @@
1
+ import { E as Extensions, ae as AgentCard, x as MessageSendParams, F as Message, ay as Task, aQ as TaskStatusUpdateEvent, aS as TaskArtifactUpdateEvent, X as TaskQueryParams, Z as TaskIdParams, $ as TaskPushNotificationConfig, a3 as GetTaskPushNotificationConfigParams, a7 as ListTaskPushNotificationConfigParams, a9 as DeleteTaskPushNotificationConfigParams } from './extensions-DvruCIzw.js';
2
+
3
+ /**
4
+ * Represents a user accessing A2A server.
5
+ */
6
+ interface User {
7
+ /**
8
+ * Indicates whether the user is authenticated.
9
+ */
10
+ get isAuthenticated(): boolean;
11
+ /**
12
+ * A unique name (identifier) for the user.
13
+ */
14
+ get userName(): string;
15
+ }
16
+ /**
17
+ * An implementation of {@link User} representing an unauthenticated user.
18
+ */
19
+ declare class UnauthenticatedUser implements User {
20
+ get isAuthenticated(): boolean;
21
+ get userName(): string;
22
+ }
23
+
24
+ declare class ServerCallContext {
25
+ private readonly _requestedExtensions?;
26
+ private readonly _user?;
27
+ private _activatedExtensions?;
28
+ constructor(requestedExtensions?: Extensions, user?: User);
29
+ get user(): User | undefined;
30
+ get activatedExtensions(): Extensions | undefined;
31
+ get requestedExtensions(): Extensions | undefined;
32
+ addActivatedExtension(uri: string): void;
33
+ }
34
+
35
+ interface A2ARequestHandler {
36
+ getAgentCard(): Promise<AgentCard>;
37
+ getAuthenticatedExtendedAgentCard(context?: ServerCallContext): Promise<AgentCard>;
38
+ sendMessage(params: MessageSendParams, context?: ServerCallContext): Promise<Message | Task>;
39
+ sendMessageStream(params: MessageSendParams, context?: ServerCallContext): AsyncGenerator<Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent, void, undefined>;
40
+ getTask(params: TaskQueryParams, context?: ServerCallContext): Promise<Task>;
41
+ cancelTask(params: TaskIdParams, context?: ServerCallContext): Promise<Task>;
42
+ setTaskPushNotificationConfig(params: TaskPushNotificationConfig, context?: ServerCallContext): Promise<TaskPushNotificationConfig>;
43
+ getTaskPushNotificationConfig(params: TaskIdParams | GetTaskPushNotificationConfigParams, context?: ServerCallContext): Promise<TaskPushNotificationConfig>;
44
+ listTaskPushNotificationConfigs(params: ListTaskPushNotificationConfigParams, context?: ServerCallContext): Promise<TaskPushNotificationConfig[]>;
45
+ deleteTaskPushNotificationConfig(params: DeleteTaskPushNotificationConfigParams, context?: ServerCallContext): Promise<void>;
46
+ resubscribe(params: TaskIdParams, context?: ServerCallContext): AsyncGenerator<Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent, void, undefined>;
47
+ }
48
+
49
+ export { type A2ARequestHandler as A, ServerCallContext as S, type User as U, UnauthenticatedUser as a };
@@ -0,0 +1,8 @@
1
+ // src/constants.ts
2
+ var AGENT_CARD_PATH = ".well-known/agent-card.json";
3
+ var HTTP_EXTENSION_HEADER = "X-A2A-Extensions";
4
+
5
+ export {
6
+ AGENT_CARD_PATH,
7
+ HTTP_EXTENSION_HEADER
8
+ };
@@ -1,3 +1,7 @@
1
+ import {
2
+ Extensions
3
+ } from "./chunk-ZX6KNMCP.js";
4
+
1
5
  // src/server/error.ts
2
6
  var A2AError = class _A2AError extends Error {
3
7
  code;
@@ -32,10 +36,7 @@ var A2AError = class _A2AError extends Error {
32
36
  return new _A2AError(-32600, message, data);
33
37
  }
34
38
  static methodNotFound(method) {
35
- return new _A2AError(
36
- -32601,
37
- `Method not found: ${method}`
38
- );
39
+ return new _A2AError(-32601, `Method not found: ${method}`);
39
40
  }
40
41
  static invalidParams(message, data) {
41
42
  return new _A2AError(-32602, message, data);
@@ -44,42 +45,46 @@ var A2AError = class _A2AError extends Error {
44
45
  return new _A2AError(-32603, message, data);
45
46
  }
46
47
  static taskNotFound(taskId) {
47
- return new _A2AError(
48
- -32001,
49
- `Task not found: ${taskId}`,
50
- void 0,
51
- taskId
52
- );
48
+ return new _A2AError(-32001, `Task not found: ${taskId}`, void 0, taskId);
53
49
  }
54
50
  static taskNotCancelable(taskId) {
55
- return new _A2AError(
56
- -32002,
57
- `Task not cancelable: ${taskId}`,
58
- void 0,
59
- taskId
60
- );
51
+ return new _A2AError(-32002, `Task not cancelable: ${taskId}`, void 0, taskId);
61
52
  }
62
53
  static pushNotificationNotSupported() {
63
- return new _A2AError(
64
- -32003,
65
- "Push Notification is not supported"
66
- );
54
+ return new _A2AError(-32003, "Push Notification is not supported");
67
55
  }
68
56
  static unsupportedOperation(operation) {
69
- return new _A2AError(
70
- -32004,
71
- `Unsupported operation: ${operation}`
72
- );
57
+ return new _A2AError(-32004, `Unsupported operation: ${operation}`);
73
58
  }
74
59
  static authenticatedExtendedCardNotConfigured() {
75
- return new _A2AError(
76
- -32007,
77
- `Extended card not configured.`
78
- );
60
+ return new _A2AError(-32007, `Extended card not configured.`);
61
+ }
62
+ };
63
+
64
+ // src/server/context.ts
65
+ var ServerCallContext = class {
66
+ _requestedExtensions;
67
+ _user;
68
+ _activatedExtensions;
69
+ constructor(requestedExtensions, user) {
70
+ this._requestedExtensions = requestedExtensions;
71
+ this._user = user;
72
+ }
73
+ get user() {
74
+ return this._user;
75
+ }
76
+ get activatedExtensions() {
77
+ return this._activatedExtensions;
78
+ }
79
+ get requestedExtensions() {
80
+ return this._requestedExtensions;
81
+ }
82
+ addActivatedExtension(uri) {
83
+ this._activatedExtensions = Extensions.createFrom(this._activatedExtensions, uri);
79
84
  }
80
85
  };
81
86
 
82
- // src/server/transports/jsonrpc_transport_handler.ts
87
+ // src/server/transports/jsonrpc/jsonrpc_transport_handler.ts
83
88
  var JsonRpcTransportHandler = class {
84
89
  requestHandler;
85
90
  constructor(requestHandler) {
@@ -90,7 +95,7 @@ var JsonRpcTransportHandler = class {
90
95
  * For streaming methods, it returns an AsyncGenerator of JSONRPCResult.
91
96
  * For non-streaming methods, it returns a Promise of a single JSONRPCMessage (Result or ErrorResponse).
92
97
  */
93
- async handle(requestBody) {
98
+ async handle(requestBody, context) {
94
99
  let rpcRequest;
95
100
  try {
96
101
  if (typeof requestBody === "string") {
@@ -104,24 +109,18 @@ var JsonRpcTransportHandler = class {
104
109
  throw A2AError.invalidRequest("Invalid JSON-RPC Request.");
105
110
  }
106
111
  } catch (error) {
107
- const a2aError = error instanceof A2AError ? error : A2AError.parseError(error.message || "Failed to parse JSON request.");
112
+ const a2aError = error instanceof A2AError ? error : A2AError.parseError(
113
+ error instanceof SyntaxError && error.message || "Failed to parse JSON request."
114
+ );
108
115
  return {
109
116
  jsonrpc: "2.0",
110
- id: typeof rpcRequest?.id !== "undefined" ? rpcRequest.id : null,
117
+ id: rpcRequest?.id !== void 0 ? rpcRequest.id : null,
111
118
  error: a2aError.toJSONRPCError()
112
119
  };
113
120
  }
114
121
  const { method, id: requestId = null } = rpcRequest;
115
122
  try {
116
- if (method === "agent/getAuthenticatedExtendedCard") {
117
- const result = await this.requestHandler.getAuthenticatedExtendedAgentCard();
118
- return {
119
- jsonrpc: "2.0",
120
- id: requestId,
121
- result
122
- };
123
- }
124
- if (!this.paramsAreValid(rpcRequest.params)) {
123
+ if (method !== "agent/getAuthenticatedExtendedCard" && !this.paramsAreValid(rpcRequest.params)) {
125
124
  throw A2AError.invalidParams(`Invalid method parameters.`);
126
125
  }
127
126
  if (method === "message/stream" || method === "tasks/resubscribe") {
@@ -130,8 +129,8 @@ var JsonRpcTransportHandler = class {
130
129
  if (!agentCard.capabilities.streaming) {
131
130
  throw A2AError.unsupportedOperation(`Method ${method} requires streaming capability.`);
132
131
  }
133
- const agentEventStream = method === "message/stream" ? this.requestHandler.sendMessageStream(params) : this.requestHandler.resubscribe(params);
134
- return async function* jsonRpcEventStream() {
132
+ const agentEventStream = method === "message/stream" ? this.requestHandler.sendMessageStream(params, context) : this.requestHandler.resubscribe(params, context);
133
+ return (async function* jsonRpcEventStream() {
135
134
  try {
136
135
  for await (const event of agentEventStream) {
137
136
  yield {
@@ -142,43 +141,50 @@ var JsonRpcTransportHandler = class {
142
141
  };
143
142
  }
144
143
  } catch (streamError) {
145
- console.error(`Error in agent event stream for ${method} (request ${requestId}):`, streamError);
144
+ console.error(
145
+ `Error in agent event stream for ${method} (request ${requestId}):`,
146
+ streamError
147
+ );
146
148
  throw streamError;
147
149
  }
148
- }();
150
+ })();
149
151
  } else {
150
152
  let result;
151
153
  switch (method) {
152
154
  case "message/send":
153
- result = await this.requestHandler.sendMessage(rpcRequest.params);
155
+ result = await this.requestHandler.sendMessage(rpcRequest.params, context);
154
156
  break;
155
157
  case "tasks/get":
156
- result = await this.requestHandler.getTask(rpcRequest.params);
158
+ result = await this.requestHandler.getTask(rpcRequest.params, context);
157
159
  break;
158
160
  case "tasks/cancel":
159
- result = await this.requestHandler.cancelTask(rpcRequest.params);
161
+ result = await this.requestHandler.cancelTask(rpcRequest.params, context);
160
162
  break;
161
163
  case "tasks/pushNotificationConfig/set":
162
164
  result = await this.requestHandler.setTaskPushNotificationConfig(
163
- rpcRequest.params
165
+ rpcRequest.params,
166
+ context
164
167
  );
165
168
  break;
166
169
  case "tasks/pushNotificationConfig/get":
167
170
  result = await this.requestHandler.getTaskPushNotificationConfig(
168
- rpcRequest.params
171
+ rpcRequest.params,
172
+ context
169
173
  );
170
174
  break;
171
175
  case "tasks/pushNotificationConfig/delete":
172
- await this.requestHandler.deleteTaskPushNotificationConfig(
173
- rpcRequest.params
174
- );
176
+ await this.requestHandler.deleteTaskPushNotificationConfig(rpcRequest.params, context);
175
177
  result = null;
176
178
  break;
177
179
  case "tasks/pushNotificationConfig/list":
178
180
  result = await this.requestHandler.listTaskPushNotificationConfigs(
179
- rpcRequest.params
181
+ rpcRequest.params,
182
+ context
180
183
  );
181
184
  break;
185
+ case "agent/getAuthenticatedExtendedCard":
186
+ result = await this.requestHandler.getAuthenticatedExtendedAgentCard(context);
187
+ break;
182
188
  default:
183
189
  throw A2AError.methodNotFound(method);
184
190
  }
@@ -189,7 +195,14 @@ var JsonRpcTransportHandler = class {
189
195
  };
190
196
  }
191
197
  } catch (error) {
192
- const a2aError = error instanceof A2AError ? error : A2AError.internalError(error.message || "An unexpected error occurred.");
198
+ let a2aError;
199
+ if (error instanceof A2AError) {
200
+ a2aError = error;
201
+ } else {
202
+ a2aError = A2AError.internalError(
203
+ error instanceof Error && error.message || "An unexpected error occurred."
204
+ );
205
+ }
193
206
  return {
194
207
  jsonrpc: "2.0",
195
208
  id: requestId,
@@ -230,7 +243,19 @@ var JsonRpcTransportHandler = class {
230
243
  }
231
244
  };
232
245
 
246
+ // src/server/authentication/user.ts
247
+ var UnauthenticatedUser = class {
248
+ get isAuthenticated() {
249
+ return false;
250
+ }
251
+ get userName() {
252
+ return "";
253
+ }
254
+ };
255
+
233
256
  export {
234
257
  A2AError,
235
- JsonRpcTransportHandler
258
+ ServerCallContext,
259
+ JsonRpcTransportHandler,
260
+ UnauthenticatedUser
236
261
  };
@@ -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
+ };
@@ -0,0 +1,38 @@
1
+ // src/extensions.ts
2
+ var Extensions = {
3
+ /**
4
+ * Creates new {@link Extensions} from `current` and `additional`.
5
+ * If `current` already contains `additional` it is returned unmodified.
6
+ */
7
+ createFrom: (current, additional) => {
8
+ if (current?.includes(additional)) {
9
+ return current;
10
+ }
11
+ return [...current ?? [], additional];
12
+ },
13
+ /**
14
+ * Creates {@link Extensions} from comma separated extensions identifiers as per
15
+ * https://a2a-protocol.org/latest/specification/#326-service-parameters.
16
+ * Parses the output of `toServiceParameter`.
17
+ */
18
+ parseServiceParameter: (value) => {
19
+ if (!value) {
20
+ return [];
21
+ }
22
+ const unique = new Set(
23
+ value.split(",").map((ext) => ext.trim()).filter((ext) => ext.length > 0)
24
+ );
25
+ return Array.from(unique);
26
+ },
27
+ /**
28
+ * Converts {@link Extensions} to comma separated extensions identifiers as per
29
+ * https://a2a-protocol.org/latest/specification/#326-service-parameters.
30
+ */
31
+ toServiceParameter: (value) => {
32
+ return value.join(",");
33
+ }
34
+ };
35
+
36
+ export {
37
+ Extensions
38
+ };