@a2a-js/sdk 0.2.1
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/LICENSE +202 -0
- package/README.md +422 -0
- package/build/src/a2a_response.d.ts +5 -0
- package/build/src/a2a_response.js +2 -0
- package/build/src/client/client.d.ts +118 -0
- package/build/src/client/client.js +409 -0
- package/build/src/index.d.ts +21 -0
- package/build/src/index.js +18 -0
- package/build/src/samples/agents/movie-agent/genkit.d.ts +2 -0
- package/build/src/samples/agents/movie-agent/genkit.js +11 -0
- package/build/src/samples/agents/movie-agent/index.d.ts +1 -0
- package/build/src/samples/agents/movie-agent/index.js +252 -0
- package/build/src/samples/agents/movie-agent/tmdb.d.ts +7 -0
- package/build/src/samples/agents/movie-agent/tmdb.js +32 -0
- package/build/src/samples/agents/movie-agent/tools.d.ts +15 -0
- package/build/src/samples/agents/movie-agent/tools.js +74 -0
- package/build/src/samples/cli.d.ts +2 -0
- package/build/src/samples/cli.js +289 -0
- package/build/src/server/a2a_express_app.d.ts +14 -0
- package/build/src/server/a2a_express_app.js +98 -0
- package/build/src/server/agent_execution/agent_executor.d.ts +18 -0
- package/build/src/server/agent_execution/agent_executor.js +2 -0
- package/build/src/server/agent_execution/request_context.d.ts +9 -0
- package/build/src/server/agent_execution/request_context.js +15 -0
- package/build/src/server/error.d.ts +23 -0
- package/build/src/server/error.js +57 -0
- package/build/src/server/events/execution_event_bus.d.ts +16 -0
- package/build/src/server/events/execution_event_bus.js +13 -0
- package/build/src/server/events/execution_event_bus_manager.d.ts +27 -0
- package/build/src/server/events/execution_event_bus_manager.js +36 -0
- package/build/src/server/events/execution_event_queue.d.ts +24 -0
- package/build/src/server/events/execution_event_queue.js +63 -0
- package/build/src/server/request_handler/a2a_request_handler.d.ts +11 -0
- package/build/src/server/request_handler/a2a_request_handler.js +2 -0
- package/build/src/server/request_handler/default_request_handler.d.ts +22 -0
- package/build/src/server/request_handler/default_request_handler.js +296 -0
- package/build/src/server/result_manager.d.ts +29 -0
- package/build/src/server/result_manager.js +149 -0
- package/build/src/server/store.d.ts +25 -0
- package/build/src/server/store.js +17 -0
- package/build/src/server/transports/jsonrpc_transport_handler.d.ts +15 -0
- package/build/src/server/transports/jsonrpc_transport_handler.js +114 -0
- package/build/src/server/utils.d.ts +22 -0
- package/build/src/server/utils.js +34 -0
- package/build/src/types-old.d.ts +832 -0
- package/build/src/types-old.js +20 -0
- package/build/src/types.d.ts +2046 -0
- package/build/src/types.js +8 -0
- package/package.json +52 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
# A2A JavaScript SDK
|
|
2
|
+
|
|
3
|
+
[](LICENSE)
|
|
4
|
+
|
|
5
|
+
<!-- markdownlint-disable no-inline-html -->
|
|
6
|
+
|
|
7
|
+
<html>
|
|
8
|
+
<h2 align="center">
|
|
9
|
+
<img src="https://raw.githubusercontent.com/google-a2a/A2A/refs/heads/main/docs/assets/a2a-logo-black.svg" width="256" alt="A2A Logo"/>
|
|
10
|
+
</h2>
|
|
11
|
+
<h3 align="center">A JavaScript library that helps run agentic applications as A2AServers following the <a href="https://google-a2a.github.io/A2A">Agent2Agent (A2A) Protocol</a>.</h3>
|
|
12
|
+
</html>
|
|
13
|
+
|
|
14
|
+
<!-- markdownlint-enable no-inline-html -->
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
You can install the A2A SDK using either `npm`.
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install @a2a-js/sdk
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
You can also find JavaScript samples [here](https://github.com/google-a2a/a2a-samples/tree/main/samples/js).
|
|
25
|
+
|
|
26
|
+
## A2A Server
|
|
27
|
+
|
|
28
|
+
This directory contains a TypeScript server implementation for the Agent-to-Agent (A2A) communication protocol, built using Express.js.
|
|
29
|
+
|
|
30
|
+
### 1. Define Agent Card
|
|
31
|
+
```typescript
|
|
32
|
+
import { AgentCard } from "@a2a-js/sdk";
|
|
33
|
+
|
|
34
|
+
const movieAgentCard: AgentCard = {
|
|
35
|
+
name: 'Movie Agent',
|
|
36
|
+
description: 'An agent that can answer questions about movies and actors using TMDB.',
|
|
37
|
+
// Adjust the base URL and port as needed.
|
|
38
|
+
url: 'http://localhost:41241/',
|
|
39
|
+
provider: {
|
|
40
|
+
organization: 'A2A Agents',
|
|
41
|
+
url: 'https://example.com/a2a-agents' // Added provider URL
|
|
42
|
+
},
|
|
43
|
+
version: '0.0.2', // Incremented version
|
|
44
|
+
capabilities: {
|
|
45
|
+
streaming: true, // Supports streaming
|
|
46
|
+
pushNotifications: false, // Assuming not implemented for this agent yet
|
|
47
|
+
stateTransitionHistory: true, // Agent uses history
|
|
48
|
+
},
|
|
49
|
+
securitySchemes: undefined, // Or define actual security schemes if any
|
|
50
|
+
security: undefined,
|
|
51
|
+
defaultInputModes: ['text/plain'],
|
|
52
|
+
defaultOutputModes: ['text/plain'],
|
|
53
|
+
skills: [
|
|
54
|
+
{
|
|
55
|
+
id: 'general_movie_chat',
|
|
56
|
+
name: 'General Movie Chat',
|
|
57
|
+
description: 'Answer general questions or chat about movies, actors, directors.',
|
|
58
|
+
tags: ['movies', 'actors', 'directors'],
|
|
59
|
+
examples: [
|
|
60
|
+
'Tell me about the plot of Inception.',
|
|
61
|
+
'Recommend a good sci-fi movie.',
|
|
62
|
+
'Who directed The Matrix?',
|
|
63
|
+
'What other movies has Scarlett Johansson been in?',
|
|
64
|
+
'Find action movies starring Keanu Reeves',
|
|
65
|
+
'Which came out first, Jurassic Park or Terminator 2?',
|
|
66
|
+
],
|
|
67
|
+
inputModes: ['text/plain'], // Explicitly defining for skill
|
|
68
|
+
outputModes: ['text/plain'] // Explicitly defining for skill
|
|
69
|
+
},
|
|
70
|
+
],
|
|
71
|
+
supportsAuthenticatedExtendedCard: false,
|
|
72
|
+
};
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### 2. Define Agent Executor
|
|
76
|
+
```typescript
|
|
77
|
+
import {
|
|
78
|
+
InMemoryTaskStore,
|
|
79
|
+
TaskStore,
|
|
80
|
+
A2AExpressApp,
|
|
81
|
+
AgentExecutor,
|
|
82
|
+
RequestContext,
|
|
83
|
+
ExecutionEventBus,
|
|
84
|
+
DefaultRequestHandler,
|
|
85
|
+
} from "@a2a-js/sdk";
|
|
86
|
+
|
|
87
|
+
// 1. Define your agent's logic as a AgentExecutor
|
|
88
|
+
class MyAgentExecutor implements AgentExecutor {
|
|
89
|
+
private cancelledTasks = new Set<string>();
|
|
90
|
+
|
|
91
|
+
public cancelTask = async (
|
|
92
|
+
taskId: string,
|
|
93
|
+
eventBus: ExecutionEventBus,
|
|
94
|
+
): Promise<void> => {
|
|
95
|
+
this.cancelledTasks.add(taskId);
|
|
96
|
+
// The execute loop is responsible for publishing the final state
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
async execute(
|
|
100
|
+
requestContext: RequestContext,
|
|
101
|
+
eventBus: ExecutionEventBus
|
|
102
|
+
): Promise<void> {
|
|
103
|
+
const userMessage = requestContext.userMessage;
|
|
104
|
+
const existingTask = requestContext.task;
|
|
105
|
+
|
|
106
|
+
// Determine IDs for the task and context, from requestContext.
|
|
107
|
+
const taskId = requestContext.taskId;
|
|
108
|
+
const contextId = requestContext.contextId;
|
|
109
|
+
|
|
110
|
+
console.log(
|
|
111
|
+
`[MyAgentExecutor] Processing message ${userMessage.messageId} for task ${taskId} (context: ${contextId})`
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
// 1. Publish initial Task event if it's a new task
|
|
115
|
+
if (!existingTask) {
|
|
116
|
+
const initialTask: Task = {
|
|
117
|
+
kind: 'task',
|
|
118
|
+
id: taskId,
|
|
119
|
+
contextId: contextId,
|
|
120
|
+
status: {
|
|
121
|
+
state: 'submitted',
|
|
122
|
+
timestamp: new Date().toISOString(),
|
|
123
|
+
},
|
|
124
|
+
history: [userMessage],
|
|
125
|
+
metadata: userMessage.metadata,
|
|
126
|
+
artifacts: [], // Initialize artifacts array
|
|
127
|
+
};
|
|
128
|
+
eventBus.publish(initialTask);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// 2. Publish "working" status update
|
|
132
|
+
const workingStatusUpdate: TaskStatusUpdateEvent = {
|
|
133
|
+
kind: 'status-update',
|
|
134
|
+
taskId: taskId,
|
|
135
|
+
contextId: contextId,
|
|
136
|
+
status: {
|
|
137
|
+
state: 'working',
|
|
138
|
+
message: {
|
|
139
|
+
kind: 'message',
|
|
140
|
+
role: 'agent',
|
|
141
|
+
messageId: uuidv4(),
|
|
142
|
+
parts: [{ kind: 'text', text: 'Generating code...' }],
|
|
143
|
+
taskId: taskId,
|
|
144
|
+
contextId: contextId,
|
|
145
|
+
},
|
|
146
|
+
timestamp: new Date().toISOString(),
|
|
147
|
+
},
|
|
148
|
+
final: false,
|
|
149
|
+
};
|
|
150
|
+
eventBus.publish(workingStatusUpdate);
|
|
151
|
+
|
|
152
|
+
// Simulate work...
|
|
153
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
154
|
+
|
|
155
|
+
// Check for request cancellation
|
|
156
|
+
if (this.cancelledTasks.has(taskId)) {
|
|
157
|
+
console.log(`[MyAgentExecutor] Request cancelled for task: ${taskId}`);
|
|
158
|
+
const cancelledUpdate: TaskStatusUpdateEvent = {
|
|
159
|
+
kind: 'status-update',
|
|
160
|
+
taskId: taskId,
|
|
161
|
+
contextId: contextId,
|
|
162
|
+
status: {
|
|
163
|
+
state: 'canceled',
|
|
164
|
+
timestamp: new Date().toISOString(),
|
|
165
|
+
},
|
|
166
|
+
final: true,
|
|
167
|
+
};
|
|
168
|
+
eventBus.publish(cancelledUpdate);
|
|
169
|
+
eventBus.finished();
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// 3. Publish artifact update
|
|
174
|
+
const artifactUpdate: TaskArtifactUpdateEvent = {
|
|
175
|
+
kind: 'artifact-update',
|
|
176
|
+
taskId: taskId,
|
|
177
|
+
contextId: contextId,
|
|
178
|
+
artifact: {
|
|
179
|
+
artifactId: "artifact-1",
|
|
180
|
+
name: "artifact-1",
|
|
181
|
+
parts: [{ text: `Task ${context.task.id} completed.` }],
|
|
182
|
+
},
|
|
183
|
+
append: false, // Each emission is a complete file snapshot
|
|
184
|
+
lastChunk: true, // True for this file artifact
|
|
185
|
+
};
|
|
186
|
+
eventBus.publish(artifactUpdate);
|
|
187
|
+
|
|
188
|
+
// 4. Publish final status update
|
|
189
|
+
const finalUpdate: TaskStatusUpdateEvent = {
|
|
190
|
+
kind: 'status-update',
|
|
191
|
+
taskId: taskId,
|
|
192
|
+
contextId: contextId,
|
|
193
|
+
status: {
|
|
194
|
+
state: 'completed',
|
|
195
|
+
message: {
|
|
196
|
+
kind: 'message',
|
|
197
|
+
role: 'agent',
|
|
198
|
+
messageId: uuidv4(),
|
|
199
|
+
taskId: taskId,
|
|
200
|
+
contextId: contextId,
|
|
201
|
+
},
|
|
202
|
+
timestamp: new Date().toISOString(),
|
|
203
|
+
},
|
|
204
|
+
final: true,
|
|
205
|
+
};
|
|
206
|
+
eventBus.publish(finalUpdate);
|
|
207
|
+
eventBus.finished();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
### 3. Start the server
|
|
213
|
+
```typescript
|
|
214
|
+
const taskStore: TaskStore = new InMemoryTaskStore();
|
|
215
|
+
const agentExecutor: AgentExecutor = new MyAgentExecutor();
|
|
216
|
+
|
|
217
|
+
const requestHandler = new DefaultRequestHandler(
|
|
218
|
+
coderAgentCard,
|
|
219
|
+
taskStore,
|
|
220
|
+
agentExecutor
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
const appBuilder = new A2AExpressApp(requestHandler);
|
|
224
|
+
const expressApp = appBuilder.setupRoutes(express(), '');
|
|
225
|
+
|
|
226
|
+
const PORT = process.env.CODER_AGENT_PORT || 41242; // Different port for coder agent
|
|
227
|
+
expressApp.listen(PORT, () => {
|
|
228
|
+
console.log(`[MyAgent] Server using new framework started on http://localhost:${PORT}`);
|
|
229
|
+
console.log(`[MyAgent] Agent Card: http://localhost:${PORT}/.well-known/agent.json`);
|
|
230
|
+
console.log('[MyAgent] Press Ctrl+C to stop the server');
|
|
231
|
+
});
|
|
232
|
+
```
|
|
233
|
+
### Agent Executor
|
|
234
|
+
Developers are expected to implement this interface and provide two methods: `execute` and `cancelTask`.
|
|
235
|
+
|
|
236
|
+
#### `execute`
|
|
237
|
+
- This method is provided with a `RequestContext` and an `EventBus` to publish execution events.
|
|
238
|
+
- Executor can either respond by publishing a Message or Task.
|
|
239
|
+
- For a task, check if there's an existing task in `RequestContext`. If not, publish an initial Task event using `taskId` & `contextId` from `RequestContext`.
|
|
240
|
+
- Executor can subsequently publish `TaskStatusUpdateEvent` or `TaskArtifactUpdateEvent`.
|
|
241
|
+
- Executor should indicate which is the `final` event and also call `finished()` method of event bus.
|
|
242
|
+
- Executor should also check if an ongoing task has been cancelled. If yes, cancel the execution and emit an `TaskStatusUpdateEvent` with cancelled state.
|
|
243
|
+
|
|
244
|
+
#### `cancelTask`
|
|
245
|
+
Executors should implement cancellation mechanism for an ongoing task.
|
|
246
|
+
|
|
247
|
+
## A2A Client
|
|
248
|
+
|
|
249
|
+
There's a `A2AClient` class, which provides methods for interacting with an A2A server over HTTP using JSON-RPC.
|
|
250
|
+
|
|
251
|
+
### Key Features:
|
|
252
|
+
|
|
253
|
+
- **JSON-RPC Communication:** Handles sending requests and receiving responses (both standard and streaming via Server-Sent Events) according to the JSON-RPC 2.0 specification.
|
|
254
|
+
- **A2A Methods:** Implements standard A2A methods like `sendMessage`, `sendMessageStream`, `getTask`, `cancelTask`, `setTaskPushNotificationConfig`, `getTaskPushNotificationConfig`, and `resubscribeTask`.
|
|
255
|
+
- **Error Handling:** Provides basic error handling for network issues and JSON-RPC errors.
|
|
256
|
+
- **Streaming Support:** Manages Server-Sent Events (SSE) for real-time task updates (`sendMessageStream`, `resubscribeTask`).
|
|
257
|
+
- **Extensibility:** Allows providing a custom `fetch` implementation for different environments (e.g., Node.js).
|
|
258
|
+
|
|
259
|
+
### Basic Usage
|
|
260
|
+
|
|
261
|
+
```typescript
|
|
262
|
+
import {
|
|
263
|
+
A2AClient,
|
|
264
|
+
Message,
|
|
265
|
+
MessageSendParams,
|
|
266
|
+
Task,
|
|
267
|
+
TaskQueryParams,
|
|
268
|
+
SendMessageResponse,
|
|
269
|
+
GetTaskResponse,
|
|
270
|
+
SendMessageSuccessResponse,
|
|
271
|
+
GetTaskSuccessResponse
|
|
272
|
+
} from "@a2a-js/sdk";
|
|
273
|
+
import { v4 as uuidv4 } from "uuid";
|
|
274
|
+
|
|
275
|
+
const client = new A2AClient("http://localhost:41241"); // Replace with your server URL
|
|
276
|
+
|
|
277
|
+
async function run() {
|
|
278
|
+
const messageId = uuidv4();
|
|
279
|
+
let taskId: string | undefined;
|
|
280
|
+
|
|
281
|
+
try {
|
|
282
|
+
// 1. Send a message to the agent.
|
|
283
|
+
const sendParams: MessageSendParams = {
|
|
284
|
+
message: {
|
|
285
|
+
messageId: messageId,
|
|
286
|
+
role: "user",
|
|
287
|
+
parts: [{ kind: "text", text: "Hello, agent!" }],
|
|
288
|
+
kind: "message"
|
|
289
|
+
},
|
|
290
|
+
configuration: {
|
|
291
|
+
blocking: true,
|
|
292
|
+
acceptedOutputModes: ['text/plain']
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
const sendResponse: SendMessageResponse = await client.sendMessage(sendParams);
|
|
297
|
+
|
|
298
|
+
if (sendResponse.error) {
|
|
299
|
+
console.error("Error sending message:", sendResponse.error);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// On success, the result can be a Task or a Message. Check which one it is.
|
|
304
|
+
const result = (sendResponse as SendMessageSuccessResponse).result;
|
|
305
|
+
|
|
306
|
+
if (result.kind === 'task') {
|
|
307
|
+
// The agent created a task.
|
|
308
|
+
const taskResult = result as Task;
|
|
309
|
+
console.log("Send Message Result (Task):", taskResult);
|
|
310
|
+
taskId = taskResult.id; // Save the task ID for the next call
|
|
311
|
+
} else if (result.kind === 'message') {
|
|
312
|
+
// The agent responded with a direct message.
|
|
313
|
+
const messageResult = result as Message;
|
|
314
|
+
console.log("Send Message Result (Direct Message):", messageResult);
|
|
315
|
+
// No task was created, so we can't get task status.
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// 2. If a task was created, get its status.
|
|
319
|
+
if (taskId) {
|
|
320
|
+
const getParams: TaskQueryParams = { id: taskId };
|
|
321
|
+
const getResponse: GetTaskResponse = await client.getTask(getParams);
|
|
322
|
+
|
|
323
|
+
if (getResponse.error) {
|
|
324
|
+
console.error(`Error getting task ${taskId}:`, getResponse.error);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const getTaskResult = (getResponse as GetTaskSuccessResponse).result;
|
|
329
|
+
console.log("Get Task Result:", getTaskResult);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
} catch (error) {
|
|
333
|
+
console.error("A2A Client Communication Error:", error);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
run();
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
### Streaming Usage
|
|
341
|
+
|
|
342
|
+
```typescript
|
|
343
|
+
import {
|
|
344
|
+
A2AClient,
|
|
345
|
+
TaskStatusUpdateEvent,
|
|
346
|
+
TaskArtifactUpdateEvent,
|
|
347
|
+
MessageSendParams,
|
|
348
|
+
Task,
|
|
349
|
+
Message,
|
|
350
|
+
} from "@a2a-js/sdk";
|
|
351
|
+
import { v4 as uuidv4 } from "uuid";
|
|
352
|
+
|
|
353
|
+
const client = new A2AClient("http://localhost:41241");
|
|
354
|
+
|
|
355
|
+
async function streamTask() {
|
|
356
|
+
const messageId = uuidv4();
|
|
357
|
+
try {
|
|
358
|
+
console.log(`\n--- Starting streaming task for message ${messageId} ---`);
|
|
359
|
+
|
|
360
|
+
// Construct the `MessageSendParams` object.
|
|
361
|
+
const streamParams: MessageSendParams = {
|
|
362
|
+
message: {
|
|
363
|
+
messageId: messageId,
|
|
364
|
+
role: "user",
|
|
365
|
+
parts: [{ kind: "text", text: "Stream me some updates!" }],
|
|
366
|
+
kind: "message"
|
|
367
|
+
},
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
// Use the `sendMessageStream` method.
|
|
371
|
+
const stream = client.sendMessageStream(streamParams);
|
|
372
|
+
let currentTaskId: string | undefined;
|
|
373
|
+
|
|
374
|
+
for await (const event of stream) {
|
|
375
|
+
// The first event is often the Task object itself, establishing the ID.
|
|
376
|
+
if ((event as Task).kind === 'task') {
|
|
377
|
+
currentTaskId = (event as Task).id;
|
|
378
|
+
console.log(`[${currentTaskId}] Task created. Status: ${(event as Task).status.state}`);
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// Differentiate subsequent stream events.
|
|
383
|
+
if ((event as TaskStatusUpdateEvent).kind === 'status-update') {
|
|
384
|
+
const statusEvent = event as TaskStatusUpdateEvent;
|
|
385
|
+
console.log(
|
|
386
|
+
`[${statusEvent.taskId}] Status Update: ${statusEvent.status.state} - ${
|
|
387
|
+
statusEvent.status.message?.parts[0]?.text ?? ""
|
|
388
|
+
}`
|
|
389
|
+
);
|
|
390
|
+
if (statusEvent.final) {
|
|
391
|
+
console.log(`[${statusEvent.taskId}] Stream marked as final.`);
|
|
392
|
+
break; // Exit loop when server signals completion
|
|
393
|
+
}
|
|
394
|
+
} else if ((event as TaskArtifactUpdateEvent).kind === 'artifact-update') {
|
|
395
|
+
const artifactEvent = event as TaskArtifactUpdateEvent;
|
|
396
|
+
// Use artifact.name or artifact.artifactId for identification
|
|
397
|
+
console.log(
|
|
398
|
+
`[${artifactEvent.taskId}] Artifact Update: ${
|
|
399
|
+
artifactEvent.artifact.name ?? artifactEvent.artifact.artifactId
|
|
400
|
+
} - Part Count: ${artifactEvent.artifact.parts.length}`
|
|
401
|
+
);
|
|
402
|
+
} else {
|
|
403
|
+
// This could be a direct Message response if the agent doesn't create a task.
|
|
404
|
+
console.log("Received direct message response in stream:", event);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
console.log(`--- Streaming for message ${messageId} finished ---`);
|
|
408
|
+
} catch (error) {
|
|
409
|
+
console.error(`Error during streaming for message ${messageId}:`, error);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
streamTask();
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
## License
|
|
417
|
+
|
|
418
|
+
This project is licensed under the terms of the [Apache 2.0 License](https://raw.githubusercontent.com/google-a2a/a2a-python/refs/heads/main/LICENSE).
|
|
419
|
+
|
|
420
|
+
## Contributing
|
|
421
|
+
|
|
422
|
+
See [CONTRIBUTING.md](https://github.com/google-a2a/a2a-js/blob/main/CONTRIBUTING.md) for contribution guidelines.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { SendMessageResponse, SendStreamingMessageResponse, GetTaskResponse, CancelTaskResponse, SetTaskPushNotificationConfigResponse, GetTaskPushNotificationConfigResponse, JSONRPCErrorResponse } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Represents any valid JSON-RPC response defined in the A2A protocol.
|
|
4
|
+
*/
|
|
5
|
+
export type A2AResponse = SendMessageResponse | SendStreamingMessageResponse | GetTaskResponse | CancelTaskResponse | SetTaskPushNotificationConfigResponse | GetTaskPushNotificationConfigResponse | JSONRPCErrorResponse;
|