@orka-js/a2a 1.5.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Orka Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,263 @@
1
+ 'use strict';
2
+
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+
10
+ // src/a2a-server.ts
11
+ var A2AServer = class {
12
+ agent;
13
+ cardConfig;
14
+ baseUrl;
15
+ constructor(config) {
16
+ this.agent = config.agent;
17
+ this.cardConfig = config.card;
18
+ this.baseUrl = config.baseUrl ?? "http://localhost:3000";
19
+ }
20
+ getAgentCard() {
21
+ return {
22
+ ...this.cardConfig,
23
+ url: this.baseUrl
24
+ };
25
+ }
26
+ /**
27
+ * Returns an Express middleware (Router) that handles A2A protocol requests.
28
+ */
29
+ handler() {
30
+ const { Router } = __require("express");
31
+ const router = Router();
32
+ router.get("/.well-known/agent.json", (_req, res) => {
33
+ res.json(this.getAgentCard());
34
+ });
35
+ router.post("/", async (req, res) => {
36
+ const body = req.body;
37
+ if (body.jsonrpc !== "2.0" || !body.method) {
38
+ res.json(this.rpcError(body.id ?? 0, -32600, "Invalid Request"));
39
+ return;
40
+ }
41
+ switch (body.method) {
42
+ case "tasks/send":
43
+ await this.handleTaskSend(body, res);
44
+ break;
45
+ case "tasks/sendSubscribe":
46
+ await this.handleTaskSubscribe(body, req, res);
47
+ break;
48
+ default:
49
+ res.json(this.rpcError(body.id, -32601, `Method not found: ${body.method}`));
50
+ }
51
+ });
52
+ return router;
53
+ }
54
+ async handleTaskSend(req, res) {
55
+ const task = req.params;
56
+ const input = task.message.parts.map((p) => p.text).join("\n");
57
+ try {
58
+ const result = await this.agent.run(input);
59
+ const taskState = {
60
+ id: task.id,
61
+ sessionId: task.sessionId,
62
+ status: { state: "completed", timestamp: (/* @__PURE__ */ new Date()).toISOString() },
63
+ artifacts: [{
64
+ parts: [{ type: "text", text: result.output }]
65
+ }]
66
+ };
67
+ const response = {
68
+ jsonrpc: "2.0",
69
+ id: req.id,
70
+ result: taskState
71
+ };
72
+ res.json(response);
73
+ } catch (error) {
74
+ res.json(this.rpcError(req.id, -32e3, error.message));
75
+ }
76
+ }
77
+ async handleTaskSubscribe(req, _expressReq, res) {
78
+ const task = req.params;
79
+ const input = task.message.parts.map((p) => p.text).join("\n");
80
+ res.setHeader("Content-Type", "text/event-stream");
81
+ res.setHeader("Cache-Control", "no-cache");
82
+ res.setHeader("Connection", "keep-alive");
83
+ res.flushHeaders();
84
+ const sendEvent = (data) => {
85
+ res.write(`data: ${JSON.stringify(data)}
86
+
87
+ `);
88
+ };
89
+ sendEvent({
90
+ jsonrpc: "2.0",
91
+ id: req.id,
92
+ result: {
93
+ id: task.id,
94
+ status: { state: "working", timestamp: (/* @__PURE__ */ new Date()).toISOString() }
95
+ }
96
+ });
97
+ try {
98
+ if (typeof this.agent.runStream === "function") {
99
+ const streamAgent = this.agent;
100
+ let fullContent = "";
101
+ for await (const event of streamAgent.runStream(input)) {
102
+ if (event.type === "token" && event.token) {
103
+ fullContent += event.token;
104
+ sendEvent({
105
+ jsonrpc: "2.0",
106
+ id: req.id,
107
+ result: {
108
+ id: task.id,
109
+ status: {
110
+ state: "working",
111
+ message: { role: "agent", parts: [{ type: "text", text: fullContent }] },
112
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
113
+ }
114
+ }
115
+ });
116
+ } else if (event.type === "done") {
117
+ fullContent = event.content ?? fullContent;
118
+ }
119
+ }
120
+ sendEvent({
121
+ jsonrpc: "2.0",
122
+ id: req.id,
123
+ result: {
124
+ id: task.id,
125
+ status: { state: "completed", timestamp: (/* @__PURE__ */ new Date()).toISOString() },
126
+ artifacts: [{ parts: [{ type: "text", text: fullContent }] }]
127
+ }
128
+ });
129
+ } else {
130
+ const result = await this.agent.run(input);
131
+ sendEvent({
132
+ jsonrpc: "2.0",
133
+ id: req.id,
134
+ result: {
135
+ id: task.id,
136
+ status: { state: "completed", timestamp: (/* @__PURE__ */ new Date()).toISOString() },
137
+ artifacts: [{ parts: [{ type: "text", text: result.output }] }]
138
+ }
139
+ });
140
+ }
141
+ } catch (error) {
142
+ sendEvent(this.rpcError(req.id, -32e3, error.message));
143
+ } finally {
144
+ res.end();
145
+ }
146
+ }
147
+ rpcError(id, code, message) {
148
+ return { jsonrpc: "2.0", id, error: { code, message } };
149
+ }
150
+ };
151
+
152
+ // src/a2a-client.ts
153
+ var _idCounter = 1;
154
+ var A2AClient = class {
155
+ baseUrl;
156
+ timeoutMs;
157
+ constructor(config) {
158
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
159
+ this.timeoutMs = config.timeoutMs ?? 6e4;
160
+ }
161
+ /** Fetch the agent card from the remote agent. */
162
+ async getAgentCard() {
163
+ const res = await fetch(`${this.baseUrl}/.well-known/agent.json`);
164
+ if (!res.ok) {
165
+ throw new Error(`Failed to fetch agent card: ${res.status}`);
166
+ }
167
+ return res.json();
168
+ }
169
+ /**
170
+ * Send a task and wait for the completed result (non-streaming).
171
+ */
172
+ async sendTask(input, sessionId) {
173
+ const task = {
174
+ id: `task-${Date.now()}`,
175
+ sessionId,
176
+ message: { role: "user", parts: [{ type: "text", text: input }] }
177
+ };
178
+ const rpcReq = {
179
+ jsonrpc: "2.0",
180
+ id: _idCounter++,
181
+ method: "tasks/send",
182
+ params: task
183
+ };
184
+ const controller = new AbortController();
185
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
186
+ let res;
187
+ try {
188
+ res = await fetch(this.baseUrl, {
189
+ method: "POST",
190
+ signal: controller.signal,
191
+ headers: { "Content-Type": "application/json" },
192
+ body: JSON.stringify(rpcReq)
193
+ });
194
+ } finally {
195
+ clearTimeout(timeout);
196
+ }
197
+ if (!res.ok) {
198
+ throw new Error(`A2A request failed: ${res.status}`);
199
+ }
200
+ const rpcRes = await res.json();
201
+ if (rpcRes.error) {
202
+ throw new Error(`A2A error ${rpcRes.error.code}: ${rpcRes.error.message}`);
203
+ }
204
+ return rpcRes.result;
205
+ }
206
+ /**
207
+ * Send a task with streaming (SSE) and yield task state updates.
208
+ */
209
+ async *sendTaskStream(input, sessionId) {
210
+ const task = {
211
+ id: `task-${Date.now()}`,
212
+ sessionId,
213
+ message: { role: "user", parts: [{ type: "text", text: input }] }
214
+ };
215
+ const rpcReq = {
216
+ jsonrpc: "2.0",
217
+ id: _idCounter++,
218
+ method: "tasks/sendSubscribe",
219
+ params: task
220
+ };
221
+ const res = await fetch(this.baseUrl, {
222
+ method: "POST",
223
+ headers: { "Content-Type": "application/json" },
224
+ body: JSON.stringify(rpcReq)
225
+ });
226
+ if (!res.ok || !res.body) {
227
+ throw new Error(`A2A stream request failed: ${res.status}`);
228
+ }
229
+ const reader = res.body.getReader();
230
+ const decoder = new TextDecoder();
231
+ let buffer = "";
232
+ try {
233
+ while (true) {
234
+ const { done, value } = await reader.read();
235
+ if (done) break;
236
+ buffer += decoder.decode(value, { stream: true });
237
+ const lines = buffer.split("\n");
238
+ buffer = lines.pop() ?? "";
239
+ for (const line of lines) {
240
+ if (!line.startsWith("data: ")) continue;
241
+ try {
242
+ const rpcRes = JSON.parse(line.slice(6));
243
+ if (rpcRes.error) {
244
+ throw new Error(`A2A error ${rpcRes.error.code}: ${rpcRes.error.message}`);
245
+ }
246
+ if (rpcRes.result) {
247
+ yield rpcRes.result;
248
+ }
249
+ } catch (e) {
250
+ if (e.message.includes("A2A error")) throw e;
251
+ }
252
+ }
253
+ }
254
+ } finally {
255
+ reader.releaseLock();
256
+ }
257
+ }
258
+ };
259
+
260
+ exports.A2AClient = A2AClient;
261
+ exports.A2AServer = A2AServer;
262
+ //# sourceMappingURL=index.cjs.map
263
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/a2a-server.ts","../src/a2a-client.ts"],"names":[],"mappings":";;;;;;;;;;AAuCO,IAAM,YAAN,MAAgB;AAAA,EACb,KAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EAER,YAAY,MAAA,EAAyB;AACnC,IAAA,IAAA,CAAK,QAAQ,MAAA,CAAO,KAAA;AACpB,IAAA,IAAA,CAAK,aAAa,MAAA,CAAO,IAAA;AACzB,IAAA,IAAA,CAAK,OAAA,GAAU,OAAO,OAAA,IAAW,uBAAA;AAAA,EACnC;AAAA,EAEA,YAAA,GAA0B;AACxB,IAAA,OAAO;AAAA,MACL,GAAG,IAAA,CAAK,UAAA;AAAA,MACR,KAAK,IAAA,CAAK;AAAA,KACZ;AAAA,EACF;AAAA;AAAA;AAAA;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Q,MAAA,CAAO,KAAA,EAAO,EAAE,MAAA,EAAQ,MAAM,CAAA;AAChD,QAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,CAAM,IAAI,CAAA;AAC/B,QAAA,MAAA,GAAS,KAAA,CAAM,KAAI,IAAK,EAAA;AAExB,QAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,UAAA,IAAI,CAAC,IAAA,CAAK,UAAA,CAAW,QAAQ,CAAA,EAAG;AAChC,UAAA,IAAI;AACF,YAAA,MAAM,SAAS,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AACvC,YAAA,IAAI,OAAO,KAAA,EAAO;AAChB,cAAA,MAAM,IAAI,KAAA,CAAM,CAAA,UAAA,EAAa,MAAA,CAAO,KAAA,CAAM,IAAI,CAAA,EAAA,EAAK,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,YAC3E;AACA,YAAA,IAAI,OAAO,MAAA,EAAQ;AACjB,cAAA,MAAM,MAAA,CAAO,MAAA;AAAA,YACf;AAAA,UACF,SAAS,CAAA,EAAG;AACV,YAAA,IAAK,CAAA,CAAY,OAAA,CAAQ,QAAA,CAAS,WAAW,GAAG,MAAM,CAAA;AAAA,UAExD;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAA,SAAE;AACA,MAAA,MAAA,CAAO,WAAA,EAAY;AAAA,IACrB;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["import type { BaseAgent } from '@orka-js/agent';\nimport type {\n AgentCard,\n A2ATask,\n A2ATaskState,\n JsonRpcRequest,\n JsonRpcResponse,\n} from './types.js';\n\nexport interface A2AServerConfig {\n agent: BaseAgent;\n card: Omit<AgentCard, 'url'>;\n /** Base URL where this server is accessible (used in agent card) */\n baseUrl?: string;\n}\n\n/**\n * Exposes an OrkaJS agent via the Google A2A protocol (JSON-RPC 2.0 over HTTP).\n *\n * Endpoints:\n * - `GET /.well-known/agent.json` — Agent Card\n * - `POST /` — `tasks/send` and `tasks/sendSubscribe` (SSE)\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { A2AServer } from '@orka-js/a2a';\n *\n * const server = new A2AServer({\n * agent: myAgent,\n * card: { name: 'Assistant', description: '...', version: '1.0.0', capabilities: {...}, skills: [] },\n * baseUrl: 'http://localhost:3000',\n * });\n *\n * const app = express();\n * app.use(server.handler());\n * app.listen(3000);\n * ```\n */\nexport class A2AServer {\n private agent: BaseAgent;\n private cardConfig: Omit<AgentCard, 'url'>;\n private baseUrl: string;\n\n constructor(config: A2AServerConfig) {\n this.agent = config.agent;\n this.cardConfig = config.card;\n this.baseUrl = config.baseUrl ?? 'http://localhost:3000';\n }\n\n getAgentCard(): AgentCard {\n return {\n ...this.cardConfig,\n url: this.baseUrl,\n };\n }\n\n /**\n * Returns an Express middleware (Router) that handles A2A protocol requests.\n */\n handler(): import('express').Router {\n const { Router } = require('express') as typeof import('express');\n const router = Router();\n\n // Agent Card endpoint\n router.get('/.well-known/agent.json', (_req: import('express').Request, res: import('express').Response) => {\n res.json(this.getAgentCard());\n });\n\n // JSON-RPC 2.0 endpoint\n router.post('/', async (req: import('express').Request, res: import('express').Response) => {\n const body = req.body as JsonRpcRequest;\n\n if (body.jsonrpc !== '2.0' || !body.method) {\n res.json(this.rpcError(body.id ?? 0, -32600, 'Invalid Request'));\n return;\n }\n\n switch (body.method) {\n case 'tasks/send':\n await this.handleTaskSend(body, res);\n break;\n case 'tasks/sendSubscribe':\n await this.handleTaskSubscribe(body, req, res);\n break;\n default:\n res.json(this.rpcError(body.id, -32601, `Method not found: ${body.method}`));\n }\n });\n\n return router;\n }\n\n private async handleTaskSend(\n req: JsonRpcRequest,\n res: import('express').Response,\n ): Promise<void> {\n const task = req.params as A2ATask;\n const input = task.message.parts.map(p => p.text).join('\\n');\n\n try {\n const result = await this.agent.run(input);\n\n const taskState: A2ATaskState = {\n id: task.id,\n sessionId: task.sessionId,\n status: { state: 'completed', timestamp: new Date().toISOString() },\n artifacts: [{\n parts: [{ type: 'text', text: result.output }],\n }],\n };\n\n const response: JsonRpcResponse = {\n jsonrpc: '2.0',\n id: req.id,\n result: taskState,\n };\n res.json(response);\n } catch (error) {\n res.json(this.rpcError(req.id, -32000, (error as Error).message));\n }\n }\n\n private async handleTaskSubscribe(\n req: JsonRpcRequest,\n _expressReq: import('express').Request,\n res: import('express').Response,\n ): Promise<void> {\n const task = req.params as A2ATask;\n const input = task.message.parts.map(p => p.text).join('\\n');\n\n res.setHeader('Content-Type', 'text/event-stream');\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Connection', 'keep-alive');\n res.flushHeaders();\n\n const sendEvent = (data: unknown) => {\n res.write(`data: ${JSON.stringify(data)}\\n\\n`);\n };\n\n // Send \"working\" status\n sendEvent({\n jsonrpc: '2.0',\n id: req.id,\n result: {\n id: task.id,\n status: { state: 'working', timestamp: new Date().toISOString() },\n } satisfies A2ATaskState,\n });\n\n try {\n if (typeof (this.agent as { runStream?: unknown }).runStream === 'function') {\n const streamAgent = this.agent as unknown as { runStream(input: string): AsyncIterable<{ type: string; token?: string; content?: string }> };\n let fullContent = '';\n\n for await (const event of streamAgent.runStream(input)) {\n if (event.type === 'token' && event.token) {\n fullContent += event.token;\n sendEvent({\n jsonrpc: '2.0',\n id: req.id,\n result: {\n id: task.id,\n status: {\n state: 'working',\n message: { role: 'agent', parts: [{ type: 'text', text: fullContent }] },\n timestamp: new Date().toISOString(),\n },\n } satisfies A2ATaskState,\n });\n } else if (event.type === 'done') {\n fullContent = event.content ?? fullContent;\n }\n }\n\n sendEvent({\n jsonrpc: '2.0',\n id: req.id,\n result: {\n id: task.id,\n status: { state: 'completed', timestamp: new Date().toISOString() },\n artifacts: [{ parts: [{ type: 'text', text: fullContent }] }],\n } satisfies A2ATaskState,\n });\n } else {\n const result = await this.agent.run(input);\n sendEvent({\n jsonrpc: '2.0',\n id: req.id,\n result: {\n id: task.id,\n status: { state: 'completed', timestamp: new Date().toISOString() },\n artifacts: [{ parts: [{ type: 'text', text: result.output }] }],\n } satisfies A2ATaskState,\n });\n }\n } catch (error) {\n sendEvent(this.rpcError(req.id, -32000, (error as Error).message));\n } finally {\n res.end();\n }\n }\n\n private rpcError(id: string | number, code: number, message: string): JsonRpcResponse {\n return { jsonrpc: '2.0', id, error: { code, message } };\n }\n}\n","import type {\n AgentCard,\n A2ATask,\n A2ATaskState,\n JsonRpcRequest,\n JsonRpcResponse,\n} from './types.js';\n\nexport interface A2AClientConfig {\n /** Base URL of the remote A2A agent */\n baseUrl: string;\n timeoutMs?: number;\n}\n\nlet _idCounter = 1;\n\n/**\n * Client for communicating with remote A2A-compatible agents.\n *\n * @example\n * ```typescript\n * const client = new A2AClient({ baseUrl: 'http://remote-agent:3000' });\n * const card = await client.getAgentCard();\n * const result = await client.sendTask('What is the weather in Paris?');\n * console.log(result.artifacts?.[0].parts[0].text);\n * ```\n */\nexport class A2AClient {\n private baseUrl: string;\n private timeoutMs: number;\n\n constructor(config: A2AClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, '');\n this.timeoutMs = config.timeoutMs ?? 60_000;\n }\n\n /** Fetch the agent card from the remote agent. */\n async getAgentCard(): Promise<AgentCard> {\n const res = await fetch(`${this.baseUrl}/.well-known/agent.json`);\n if (!res.ok) {\n throw new Error(`Failed to fetch agent card: ${res.status}`);\n }\n return res.json() as Promise<AgentCard>;\n }\n\n /**\n * Send a task and wait for the completed result (non-streaming).\n */\n async sendTask(\n input: string,\n sessionId?: string,\n ): Promise<A2ATaskState> {\n const task: A2ATask = {\n id: `task-${Date.now()}`,\n sessionId,\n message: { role: 'user', parts: [{ type: 'text', text: input }] },\n };\n\n const rpcReq: JsonRpcRequest = {\n jsonrpc: '2.0',\n id: _idCounter++,\n method: 'tasks/send',\n params: task,\n };\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let res: Response;\n try {\n res = await fetch(this.baseUrl, {\n method: 'POST',\n signal: controller.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(rpcReq),\n });\n } finally {\n clearTimeout(timeout);\n }\n\n if (!res.ok) {\n throw new Error(`A2A request failed: ${res.status}`);\n }\n\n const rpcRes = await res.json() as JsonRpcResponse;\n if (rpcRes.error) {\n throw new Error(`A2A error ${rpcRes.error.code}: ${rpcRes.error.message}`);\n }\n\n return rpcRes.result as A2ATaskState;\n }\n\n /**\n * Send a task with streaming (SSE) and yield task state updates.\n */\n async *sendTaskStream(\n input: string,\n sessionId?: string,\n ): AsyncIterable<A2ATaskState> {\n const task: A2ATask = {\n id: `task-${Date.now()}`,\n sessionId,\n message: { role: 'user', parts: [{ type: 'text', text: input }] },\n };\n\n const rpcReq: JsonRpcRequest = {\n jsonrpc: '2.0',\n id: _idCounter++,\n method: 'tasks/sendSubscribe',\n params: task,\n };\n\n const res = await fetch(this.baseUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(rpcReq),\n });\n\n if (!res.ok || !res.body) {\n throw new Error(`A2A stream request failed: ${res.status}`);\n }\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (!line.startsWith('data: ')) continue;\n try {\n const rpcRes = JSON.parse(line.slice(6)) as JsonRpcResponse;\n if (rpcRes.error) {\n throw new Error(`A2A error ${rpcRes.error.code}: ${rpcRes.error.message}`);\n }\n if (rpcRes.result) {\n yield rpcRes.result as A2ATaskState;\n }\n } catch (e) {\n if ((e as Error).message.includes('A2A error')) throw e;\n // Skip malformed SSE lines\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n}\n"]}
@@ -0,0 +1,150 @@
1
+ import * as express from 'express';
2
+ import { BaseAgent } from '@orka-js/agent';
3
+
4
+ /**
5
+ * A2A Protocol types — based on Google's Agent-to-Agent open specification.
6
+ * @see https://github.com/google/A2A
7
+ */
8
+ interface AgentCard {
9
+ name: string;
10
+ description: string;
11
+ version: string;
12
+ url: string;
13
+ capabilities: {
14
+ streaming: boolean;
15
+ tools: boolean;
16
+ multiModal: boolean;
17
+ };
18
+ skills: AgentSkill[];
19
+ }
20
+ interface AgentSkill {
21
+ id: string;
22
+ name: string;
23
+ description: string;
24
+ inputModes?: string[];
25
+ outputModes?: string[];
26
+ }
27
+ interface A2AMessagePart {
28
+ type: 'text';
29
+ text: string;
30
+ }
31
+ interface A2AMessage {
32
+ role: 'user' | 'agent';
33
+ parts: A2AMessagePart[];
34
+ }
35
+ interface A2ATask {
36
+ id: string;
37
+ sessionId?: string;
38
+ message: A2AMessage;
39
+ }
40
+ interface A2AArtifact {
41
+ name?: string;
42
+ parts: A2AMessagePart[];
43
+ }
44
+ type A2ATaskStatus = 'submitted' | 'working' | 'completed' | 'failed' | 'canceled';
45
+ interface A2ATaskState {
46
+ id: string;
47
+ sessionId?: string;
48
+ status: {
49
+ state: A2ATaskStatus;
50
+ message?: A2AMessage;
51
+ timestamp?: string;
52
+ };
53
+ artifacts?: A2AArtifact[];
54
+ }
55
+ /** JSON-RPC 2.0 request */
56
+ interface JsonRpcRequest {
57
+ jsonrpc: '2.0';
58
+ id: string | number;
59
+ method: string;
60
+ params?: unknown;
61
+ }
62
+ /** JSON-RPC 2.0 response */
63
+ interface JsonRpcResponse {
64
+ jsonrpc: '2.0';
65
+ id: string | number;
66
+ result?: unknown;
67
+ error?: {
68
+ code: number;
69
+ message: string;
70
+ data?: unknown;
71
+ };
72
+ }
73
+
74
+ interface A2AServerConfig {
75
+ agent: BaseAgent;
76
+ card: Omit<AgentCard, 'url'>;
77
+ /** Base URL where this server is accessible (used in agent card) */
78
+ baseUrl?: string;
79
+ }
80
+ /**
81
+ * Exposes an OrkaJS agent via the Google A2A protocol (JSON-RPC 2.0 over HTTP).
82
+ *
83
+ * Endpoints:
84
+ * - `GET /.well-known/agent.json` — Agent Card
85
+ * - `POST /` — `tasks/send` and `tasks/sendSubscribe` (SSE)
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * import express from 'express';
90
+ * import { A2AServer } from '@orka-js/a2a';
91
+ *
92
+ * const server = new A2AServer({
93
+ * agent: myAgent,
94
+ * card: { name: 'Assistant', description: '...', version: '1.0.0', capabilities: {...}, skills: [] },
95
+ * baseUrl: 'http://localhost:3000',
96
+ * });
97
+ *
98
+ * const app = express();
99
+ * app.use(server.handler());
100
+ * app.listen(3000);
101
+ * ```
102
+ */
103
+ declare class A2AServer {
104
+ private agent;
105
+ private cardConfig;
106
+ private baseUrl;
107
+ constructor(config: A2AServerConfig);
108
+ getAgentCard(): AgentCard;
109
+ /**
110
+ * Returns an Express middleware (Router) that handles A2A protocol requests.
111
+ */
112
+ handler(): express.Router;
113
+ private handleTaskSend;
114
+ private handleTaskSubscribe;
115
+ private rpcError;
116
+ }
117
+
118
+ interface A2AClientConfig {
119
+ /** Base URL of the remote A2A agent */
120
+ baseUrl: string;
121
+ timeoutMs?: number;
122
+ }
123
+ /**
124
+ * Client for communicating with remote A2A-compatible agents.
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * const client = new A2AClient({ baseUrl: 'http://remote-agent:3000' });
129
+ * const card = await client.getAgentCard();
130
+ * const result = await client.sendTask('What is the weather in Paris?');
131
+ * console.log(result.artifacts?.[0].parts[0].text);
132
+ * ```
133
+ */
134
+ declare class A2AClient {
135
+ private baseUrl;
136
+ private timeoutMs;
137
+ constructor(config: A2AClientConfig);
138
+ /** Fetch the agent card from the remote agent. */
139
+ getAgentCard(): Promise<AgentCard>;
140
+ /**
141
+ * Send a task and wait for the completed result (non-streaming).
142
+ */
143
+ sendTask(input: string, sessionId?: string): Promise<A2ATaskState>;
144
+ /**
145
+ * Send a task with streaming (SSE) and yield task state updates.
146
+ */
147
+ sendTaskStream(input: string, sessionId?: string): AsyncIterable<A2ATaskState>;
148
+ }
149
+
150
+ export { type A2AArtifact, A2AClient, type A2AClientConfig, type A2AMessage, type A2AMessagePart, A2AServer, type A2AServerConfig, type A2ATask, type A2ATaskState, type A2ATaskStatus, type AgentCard, type AgentSkill, type JsonRpcRequest, type JsonRpcResponse };
@@ -0,0 +1,150 @@
1
+ import * as express from 'express';
2
+ import { BaseAgent } from '@orka-js/agent';
3
+
4
+ /**
5
+ * A2A Protocol types — based on Google's Agent-to-Agent open specification.
6
+ * @see https://github.com/google/A2A
7
+ */
8
+ interface AgentCard {
9
+ name: string;
10
+ description: string;
11
+ version: string;
12
+ url: string;
13
+ capabilities: {
14
+ streaming: boolean;
15
+ tools: boolean;
16
+ multiModal: boolean;
17
+ };
18
+ skills: AgentSkill[];
19
+ }
20
+ interface AgentSkill {
21
+ id: string;
22
+ name: string;
23
+ description: string;
24
+ inputModes?: string[];
25
+ outputModes?: string[];
26
+ }
27
+ interface A2AMessagePart {
28
+ type: 'text';
29
+ text: string;
30
+ }
31
+ interface A2AMessage {
32
+ role: 'user' | 'agent';
33
+ parts: A2AMessagePart[];
34
+ }
35
+ interface A2ATask {
36
+ id: string;
37
+ sessionId?: string;
38
+ message: A2AMessage;
39
+ }
40
+ interface A2AArtifact {
41
+ name?: string;
42
+ parts: A2AMessagePart[];
43
+ }
44
+ type A2ATaskStatus = 'submitted' | 'working' | 'completed' | 'failed' | 'canceled';
45
+ interface A2ATaskState {
46
+ id: string;
47
+ sessionId?: string;
48
+ status: {
49
+ state: A2ATaskStatus;
50
+ message?: A2AMessage;
51
+ timestamp?: string;
52
+ };
53
+ artifacts?: A2AArtifact[];
54
+ }
55
+ /** JSON-RPC 2.0 request */
56
+ interface JsonRpcRequest {
57
+ jsonrpc: '2.0';
58
+ id: string | number;
59
+ method: string;
60
+ params?: unknown;
61
+ }
62
+ /** JSON-RPC 2.0 response */
63
+ interface JsonRpcResponse {
64
+ jsonrpc: '2.0';
65
+ id: string | number;
66
+ result?: unknown;
67
+ error?: {
68
+ code: number;
69
+ message: string;
70
+ data?: unknown;
71
+ };
72
+ }
73
+
74
+ interface A2AServerConfig {
75
+ agent: BaseAgent;
76
+ card: Omit<AgentCard, 'url'>;
77
+ /** Base URL where this server is accessible (used in agent card) */
78
+ baseUrl?: string;
79
+ }
80
+ /**
81
+ * Exposes an OrkaJS agent via the Google A2A protocol (JSON-RPC 2.0 over HTTP).
82
+ *
83
+ * Endpoints:
84
+ * - `GET /.well-known/agent.json` — Agent Card
85
+ * - `POST /` — `tasks/send` and `tasks/sendSubscribe` (SSE)
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * import express from 'express';
90
+ * import { A2AServer } from '@orka-js/a2a';
91
+ *
92
+ * const server = new A2AServer({
93
+ * agent: myAgent,
94
+ * card: { name: 'Assistant', description: '...', version: '1.0.0', capabilities: {...}, skills: [] },
95
+ * baseUrl: 'http://localhost:3000',
96
+ * });
97
+ *
98
+ * const app = express();
99
+ * app.use(server.handler());
100
+ * app.listen(3000);
101
+ * ```
102
+ */
103
+ declare class A2AServer {
104
+ private agent;
105
+ private cardConfig;
106
+ private baseUrl;
107
+ constructor(config: A2AServerConfig);
108
+ getAgentCard(): AgentCard;
109
+ /**
110
+ * Returns an Express middleware (Router) that handles A2A protocol requests.
111
+ */
112
+ handler(): express.Router;
113
+ private handleTaskSend;
114
+ private handleTaskSubscribe;
115
+ private rpcError;
116
+ }
117
+
118
+ interface A2AClientConfig {
119
+ /** Base URL of the remote A2A agent */
120
+ baseUrl: string;
121
+ timeoutMs?: number;
122
+ }
123
+ /**
124
+ * Client for communicating with remote A2A-compatible agents.
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * const client = new A2AClient({ baseUrl: 'http://remote-agent:3000' });
129
+ * const card = await client.getAgentCard();
130
+ * const result = await client.sendTask('What is the weather in Paris?');
131
+ * console.log(result.artifacts?.[0].parts[0].text);
132
+ * ```
133
+ */
134
+ declare class A2AClient {
135
+ private baseUrl;
136
+ private timeoutMs;
137
+ constructor(config: A2AClientConfig);
138
+ /** Fetch the agent card from the remote agent. */
139
+ getAgentCard(): Promise<AgentCard>;
140
+ /**
141
+ * Send a task and wait for the completed result (non-streaming).
142
+ */
143
+ sendTask(input: string, sessionId?: string): Promise<A2ATaskState>;
144
+ /**
145
+ * Send a task with streaming (SSE) and yield task state updates.
146
+ */
147
+ sendTaskStream(input: string, sessionId?: string): AsyncIterable<A2ATaskState>;
148
+ }
149
+
150
+ export { type A2AArtifact, A2AClient, type A2AClientConfig, type A2AMessage, type A2AMessagePart, A2AServer, type A2AServerConfig, type A2ATask, type A2ATaskState, type A2ATaskStatus, type AgentCard, type AgentSkill, type JsonRpcRequest, type JsonRpcResponse };
package/dist/index.js ADDED
@@ -0,0 +1,260 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/a2a-server.ts
9
+ var A2AServer = class {
10
+ agent;
11
+ cardConfig;
12
+ baseUrl;
13
+ constructor(config) {
14
+ this.agent = config.agent;
15
+ this.cardConfig = config.card;
16
+ this.baseUrl = config.baseUrl ?? "http://localhost:3000";
17
+ }
18
+ getAgentCard() {
19
+ return {
20
+ ...this.cardConfig,
21
+ url: this.baseUrl
22
+ };
23
+ }
24
+ /**
25
+ * Returns an Express middleware (Router) that handles A2A protocol requests.
26
+ */
27
+ handler() {
28
+ const { Router } = __require("express");
29
+ const router = Router();
30
+ router.get("/.well-known/agent.json", (_req, res) => {
31
+ res.json(this.getAgentCard());
32
+ });
33
+ router.post("/", async (req, res) => {
34
+ const body = req.body;
35
+ if (body.jsonrpc !== "2.0" || !body.method) {
36
+ res.json(this.rpcError(body.id ?? 0, -32600, "Invalid Request"));
37
+ return;
38
+ }
39
+ switch (body.method) {
40
+ case "tasks/send":
41
+ await this.handleTaskSend(body, res);
42
+ break;
43
+ case "tasks/sendSubscribe":
44
+ await this.handleTaskSubscribe(body, req, res);
45
+ break;
46
+ default:
47
+ res.json(this.rpcError(body.id, -32601, `Method not found: ${body.method}`));
48
+ }
49
+ });
50
+ return router;
51
+ }
52
+ async handleTaskSend(req, res) {
53
+ const task = req.params;
54
+ const input = task.message.parts.map((p) => p.text).join("\n");
55
+ try {
56
+ const result = await this.agent.run(input);
57
+ const taskState = {
58
+ id: task.id,
59
+ sessionId: task.sessionId,
60
+ status: { state: "completed", timestamp: (/* @__PURE__ */ new Date()).toISOString() },
61
+ artifacts: [{
62
+ parts: [{ type: "text", text: result.output }]
63
+ }]
64
+ };
65
+ const response = {
66
+ jsonrpc: "2.0",
67
+ id: req.id,
68
+ result: taskState
69
+ };
70
+ res.json(response);
71
+ } catch (error) {
72
+ res.json(this.rpcError(req.id, -32e3, error.message));
73
+ }
74
+ }
75
+ async handleTaskSubscribe(req, _expressReq, res) {
76
+ const task = req.params;
77
+ const input = task.message.parts.map((p) => p.text).join("\n");
78
+ res.setHeader("Content-Type", "text/event-stream");
79
+ res.setHeader("Cache-Control", "no-cache");
80
+ res.setHeader("Connection", "keep-alive");
81
+ res.flushHeaders();
82
+ const sendEvent = (data) => {
83
+ res.write(`data: ${JSON.stringify(data)}
84
+
85
+ `);
86
+ };
87
+ sendEvent({
88
+ jsonrpc: "2.0",
89
+ id: req.id,
90
+ result: {
91
+ id: task.id,
92
+ status: { state: "working", timestamp: (/* @__PURE__ */ new Date()).toISOString() }
93
+ }
94
+ });
95
+ try {
96
+ if (typeof this.agent.runStream === "function") {
97
+ const streamAgent = this.agent;
98
+ let fullContent = "";
99
+ for await (const event of streamAgent.runStream(input)) {
100
+ if (event.type === "token" && event.token) {
101
+ fullContent += event.token;
102
+ sendEvent({
103
+ jsonrpc: "2.0",
104
+ id: req.id,
105
+ result: {
106
+ id: task.id,
107
+ status: {
108
+ state: "working",
109
+ message: { role: "agent", parts: [{ type: "text", text: fullContent }] },
110
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
111
+ }
112
+ }
113
+ });
114
+ } else if (event.type === "done") {
115
+ fullContent = event.content ?? fullContent;
116
+ }
117
+ }
118
+ sendEvent({
119
+ jsonrpc: "2.0",
120
+ id: req.id,
121
+ result: {
122
+ id: task.id,
123
+ status: { state: "completed", timestamp: (/* @__PURE__ */ new Date()).toISOString() },
124
+ artifacts: [{ parts: [{ type: "text", text: fullContent }] }]
125
+ }
126
+ });
127
+ } else {
128
+ const result = await this.agent.run(input);
129
+ sendEvent({
130
+ jsonrpc: "2.0",
131
+ id: req.id,
132
+ result: {
133
+ id: task.id,
134
+ status: { state: "completed", timestamp: (/* @__PURE__ */ new Date()).toISOString() },
135
+ artifacts: [{ parts: [{ type: "text", text: result.output }] }]
136
+ }
137
+ });
138
+ }
139
+ } catch (error) {
140
+ sendEvent(this.rpcError(req.id, -32e3, error.message));
141
+ } finally {
142
+ res.end();
143
+ }
144
+ }
145
+ rpcError(id, code, message) {
146
+ return { jsonrpc: "2.0", id, error: { code, message } };
147
+ }
148
+ };
149
+
150
+ // src/a2a-client.ts
151
+ var _idCounter = 1;
152
+ var A2AClient = class {
153
+ baseUrl;
154
+ timeoutMs;
155
+ constructor(config) {
156
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
157
+ this.timeoutMs = config.timeoutMs ?? 6e4;
158
+ }
159
+ /** Fetch the agent card from the remote agent. */
160
+ async getAgentCard() {
161
+ const res = await fetch(`${this.baseUrl}/.well-known/agent.json`);
162
+ if (!res.ok) {
163
+ throw new Error(`Failed to fetch agent card: ${res.status}`);
164
+ }
165
+ return res.json();
166
+ }
167
+ /**
168
+ * Send a task and wait for the completed result (non-streaming).
169
+ */
170
+ async sendTask(input, sessionId) {
171
+ const task = {
172
+ id: `task-${Date.now()}`,
173
+ sessionId,
174
+ message: { role: "user", parts: [{ type: "text", text: input }] }
175
+ };
176
+ const rpcReq = {
177
+ jsonrpc: "2.0",
178
+ id: _idCounter++,
179
+ method: "tasks/send",
180
+ params: task
181
+ };
182
+ const controller = new AbortController();
183
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
184
+ let res;
185
+ try {
186
+ res = await fetch(this.baseUrl, {
187
+ method: "POST",
188
+ signal: controller.signal,
189
+ headers: { "Content-Type": "application/json" },
190
+ body: JSON.stringify(rpcReq)
191
+ });
192
+ } finally {
193
+ clearTimeout(timeout);
194
+ }
195
+ if (!res.ok) {
196
+ throw new Error(`A2A request failed: ${res.status}`);
197
+ }
198
+ const rpcRes = await res.json();
199
+ if (rpcRes.error) {
200
+ throw new Error(`A2A error ${rpcRes.error.code}: ${rpcRes.error.message}`);
201
+ }
202
+ return rpcRes.result;
203
+ }
204
+ /**
205
+ * Send a task with streaming (SSE) and yield task state updates.
206
+ */
207
+ async *sendTaskStream(input, sessionId) {
208
+ const task = {
209
+ id: `task-${Date.now()}`,
210
+ sessionId,
211
+ message: { role: "user", parts: [{ type: "text", text: input }] }
212
+ };
213
+ const rpcReq = {
214
+ jsonrpc: "2.0",
215
+ id: _idCounter++,
216
+ method: "tasks/sendSubscribe",
217
+ params: task
218
+ };
219
+ const res = await fetch(this.baseUrl, {
220
+ method: "POST",
221
+ headers: { "Content-Type": "application/json" },
222
+ body: JSON.stringify(rpcReq)
223
+ });
224
+ if (!res.ok || !res.body) {
225
+ throw new Error(`A2A stream request failed: ${res.status}`);
226
+ }
227
+ const reader = res.body.getReader();
228
+ const decoder = new TextDecoder();
229
+ let buffer = "";
230
+ try {
231
+ while (true) {
232
+ const { done, value } = await reader.read();
233
+ if (done) break;
234
+ buffer += decoder.decode(value, { stream: true });
235
+ const lines = buffer.split("\n");
236
+ buffer = lines.pop() ?? "";
237
+ for (const line of lines) {
238
+ if (!line.startsWith("data: ")) continue;
239
+ try {
240
+ const rpcRes = JSON.parse(line.slice(6));
241
+ if (rpcRes.error) {
242
+ throw new Error(`A2A error ${rpcRes.error.code}: ${rpcRes.error.message}`);
243
+ }
244
+ if (rpcRes.result) {
245
+ yield rpcRes.result;
246
+ }
247
+ } catch (e) {
248
+ if (e.message.includes("A2A error")) throw e;
249
+ }
250
+ }
251
+ }
252
+ } finally {
253
+ reader.releaseLock();
254
+ }
255
+ }
256
+ };
257
+
258
+ export { A2AClient, A2AServer };
259
+ //# sourceMappingURL=index.js.map
260
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/a2a-server.ts","../src/a2a-client.ts"],"names":[],"mappings":";;;;;;;;AAuCO,IAAM,YAAN,MAAgB;AAAA,EACb,KAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EAER,YAAY,MAAA,EAAyB;AACnC,IAAA,IAAA,CAAK,QAAQ,MAAA,CAAO,KAAA;AACpB,IAAA,IAAA,CAAK,aAAa,MAAA,CAAO,IAAA;AACzB,IAAA,IAAA,CAAK,OAAA,GAAU,OAAO,OAAA,IAAW,uBAAA;AAAA,EACnC;AAAA,EAEA,YAAA,GAA0B;AACxB,IAAA,OAAO;AAAA,MACL,GAAG,IAAA,CAAK,UAAA;AAAA,MACR,KAAK,IAAA,CAAK;AAAA,KACZ;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,OAAA,GAAoC;AAClC,IAAA,MAAM,EAAE,MAAA,EAAO,GAAI,SAAA,CAAQ,SAAS,CAAA;AACpC,IAAA,MAAM,SAAS,MAAA,EAAO;AAGtB,IAAA,MAAA,CAAO,GAAA,CAAI,yBAAA,EAA2B,CAAC,IAAA,EAAiC,GAAA,KAAoC;AAC1G,MAAA,GAAA,CAAI,IAAA,CAAK,IAAA,CAAK,YAAA,EAAc,CAAA;AAAA,IAC9B,CAAC,CAAA;AAGD,IAAA,MAAA,CAAO,IAAA,CAAK,GAAA,EAAK,OAAO,GAAA,EAAgC,GAAA,KAAoC;AAC1F,MAAA,MAAM,OAAO,GAAA,CAAI,IAAA;AAEjB,MAAA,IAAI,IAAA,CAAK,OAAA,KAAY,KAAA,IAAS,CAAC,KAAK,MAAA,EAAQ;AAC1C,Q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,CAAA,EAAA,EAAK,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,YAC3E;AACA,YAAA,IAAI,OAAO,MAAA,EAAQ;AACjB,cAAA,MAAM,MAAA,CAAO,MAAA;AAAA,YACf;AAAA,UACF,SAAS,CAAA,EAAG;AACV,YAAA,IAAK,CAAA,CAAY,OAAA,CAAQ,QAAA,CAAS,WAAW,GAAG,MAAM,CAAA;AAAA,UAExD;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAA,SAAE;AACA,MAAA,MAAA,CAAO,WAAA,EAAY;AAAA,IACrB;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { BaseAgent } from '@orka-js/agent';\nimport type {\n AgentCard,\n A2ATask,\n A2ATaskState,\n JsonRpcRequest,\n JsonRpcResponse,\n} from './types.js';\n\nexport interface A2AServerConfig {\n agent: BaseAgent;\n card: Omit<AgentCard, 'url'>;\n /** Base URL where this server is accessible (used in agent card) */\n baseUrl?: string;\n}\n\n/**\n * Exposes an OrkaJS agent via the Google A2A protocol (JSON-RPC 2.0 over HTTP).\n *\n * Endpoints:\n * - `GET /.well-known/agent.json` — Agent Card\n * - `POST /` — `tasks/send` and `tasks/sendSubscribe` (SSE)\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { A2AServer } from '@orka-js/a2a';\n *\n * const server = new A2AServer({\n * agent: myAgent,\n * card: { name: 'Assistant', description: '...', version: '1.0.0', capabilities: {...}, skills: [] },\n * baseUrl: 'http://localhost:3000',\n * });\n *\n * const app = express();\n * app.use(server.handler());\n * app.listen(3000);\n * ```\n */\nexport class A2AServer {\n private agent: BaseAgent;\n private cardConfig: Omit<AgentCard, 'url'>;\n private baseUrl: string;\n\n constructor(config: A2AServerConfig) {\n this.agent = config.agent;\n this.cardConfig = config.card;\n this.baseUrl = config.baseUrl ?? 'http://localhost:3000';\n }\n\n getAgentCard(): AgentCard {\n return {\n ...this.cardConfig,\n url: this.baseUrl,\n };\n }\n\n /**\n * Returns an Express middleware (Router) that handles A2A protocol requests.\n */\n handler(): import('express').Router {\n const { Router } = require('express') as typeof import('express');\n const router = Router();\n\n // Agent Card endpoint\n router.get('/.well-known/agent.json', (_req: import('express').Request, res: import('express').Response) => {\n res.json(this.getAgentCard());\n });\n\n // JSON-RPC 2.0 endpoint\n router.post('/', async (req: import('express').Request, res: import('express').Response) => {\n const body = req.body as JsonRpcRequest;\n\n if (body.jsonrpc !== '2.0' || !body.method) {\n res.json(this.rpcError(body.id ?? 0, -32600, 'Invalid Request'));\n return;\n }\n\n switch (body.method) {\n case 'tasks/send':\n await this.handleTaskSend(body, res);\n break;\n case 'tasks/sendSubscribe':\n await this.handleTaskSubscribe(body, req, res);\n break;\n default:\n res.json(this.rpcError(body.id, -32601, `Method not found: ${body.method}`));\n }\n });\n\n return router;\n }\n\n private async handleTaskSend(\n req: JsonRpcRequest,\n res: import('express').Response,\n ): Promise<void> {\n const task = req.params as A2ATask;\n const input = task.message.parts.map(p => p.text).join('\\n');\n\n try {\n const result = await this.agent.run(input);\n\n const taskState: A2ATaskState = {\n id: task.id,\n sessionId: task.sessionId,\n status: { state: 'completed', timestamp: new Date().toISOString() },\n artifacts: [{\n parts: [{ type: 'text', text: result.output }],\n }],\n };\n\n const response: JsonRpcResponse = {\n jsonrpc: '2.0',\n id: req.id,\n result: taskState,\n };\n res.json(response);\n } catch (error) {\n res.json(this.rpcError(req.id, -32000, (error as Error).message));\n }\n }\n\n private async handleTaskSubscribe(\n req: JsonRpcRequest,\n _expressReq: import('express').Request,\n res: import('express').Response,\n ): Promise<void> {\n const task = req.params as A2ATask;\n const input = task.message.parts.map(p => p.text).join('\\n');\n\n res.setHeader('Content-Type', 'text/event-stream');\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Connection', 'keep-alive');\n res.flushHeaders();\n\n const sendEvent = (data: unknown) => {\n res.write(`data: ${JSON.stringify(data)}\\n\\n`);\n };\n\n // Send \"working\" status\n sendEvent({\n jsonrpc: '2.0',\n id: req.id,\n result: {\n id: task.id,\n status: { state: 'working', timestamp: new Date().toISOString() },\n } satisfies A2ATaskState,\n });\n\n try {\n if (typeof (this.agent as { runStream?: unknown }).runStream === 'function') {\n const streamAgent = this.agent as unknown as { runStream(input: string): AsyncIterable<{ type: string; token?: string; content?: string }> };\n let fullContent = '';\n\n for await (const event of streamAgent.runStream(input)) {\n if (event.type === 'token' && event.token) {\n fullContent += event.token;\n sendEvent({\n jsonrpc: '2.0',\n id: req.id,\n result: {\n id: task.id,\n status: {\n state: 'working',\n message: { role: 'agent', parts: [{ type: 'text', text: fullContent }] },\n timestamp: new Date().toISOString(),\n },\n } satisfies A2ATaskState,\n });\n } else if (event.type === 'done') {\n fullContent = event.content ?? fullContent;\n }\n }\n\n sendEvent({\n jsonrpc: '2.0',\n id: req.id,\n result: {\n id: task.id,\n status: { state: 'completed', timestamp: new Date().toISOString() },\n artifacts: [{ parts: [{ type: 'text', text: fullContent }] }],\n } satisfies A2ATaskState,\n });\n } else {\n const result = await this.agent.run(input);\n sendEvent({\n jsonrpc: '2.0',\n id: req.id,\n result: {\n id: task.id,\n status: { state: 'completed', timestamp: new Date().toISOString() },\n artifacts: [{ parts: [{ type: 'text', text: result.output }] }],\n } satisfies A2ATaskState,\n });\n }\n } catch (error) {\n sendEvent(this.rpcError(req.id, -32000, (error as Error).message));\n } finally {\n res.end();\n }\n }\n\n private rpcError(id: string | number, code: number, message: string): JsonRpcResponse {\n return { jsonrpc: '2.0', id, error: { code, message } };\n }\n}\n","import type {\n AgentCard,\n A2ATask,\n A2ATaskState,\n JsonRpcRequest,\n JsonRpcResponse,\n} from './types.js';\n\nexport interface A2AClientConfig {\n /** Base URL of the remote A2A agent */\n baseUrl: string;\n timeoutMs?: number;\n}\n\nlet _idCounter = 1;\n\n/**\n * Client for communicating with remote A2A-compatible agents.\n *\n * @example\n * ```typescript\n * const client = new A2AClient({ baseUrl: 'http://remote-agent:3000' });\n * const card = await client.getAgentCard();\n * const result = await client.sendTask('What is the weather in Paris?');\n * console.log(result.artifacts?.[0].parts[0].text);\n * ```\n */\nexport class A2AClient {\n private baseUrl: string;\n private timeoutMs: number;\n\n constructor(config: A2AClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, '');\n this.timeoutMs = config.timeoutMs ?? 60_000;\n }\n\n /** Fetch the agent card from the remote agent. */\n async getAgentCard(): Promise<AgentCard> {\n const res = await fetch(`${this.baseUrl}/.well-known/agent.json`);\n if (!res.ok) {\n throw new Error(`Failed to fetch agent card: ${res.status}`);\n }\n return res.json() as Promise<AgentCard>;\n }\n\n /**\n * Send a task and wait for the completed result (non-streaming).\n */\n async sendTask(\n input: string,\n sessionId?: string,\n ): Promise<A2ATaskState> {\n const task: A2ATask = {\n id: `task-${Date.now()}`,\n sessionId,\n message: { role: 'user', parts: [{ type: 'text', text: input }] },\n };\n\n const rpcReq: JsonRpcRequest = {\n jsonrpc: '2.0',\n id: _idCounter++,\n method: 'tasks/send',\n params: task,\n };\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let res: Response;\n try {\n res = await fetch(this.baseUrl, {\n method: 'POST',\n signal: controller.signal,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(rpcReq),\n });\n } finally {\n clearTimeout(timeout);\n }\n\n if (!res.ok) {\n throw new Error(`A2A request failed: ${res.status}`);\n }\n\n const rpcRes = await res.json() as JsonRpcResponse;\n if (rpcRes.error) {\n throw new Error(`A2A error ${rpcRes.error.code}: ${rpcRes.error.message}`);\n }\n\n return rpcRes.result as A2ATaskState;\n }\n\n /**\n * Send a task with streaming (SSE) and yield task state updates.\n */\n async *sendTaskStream(\n input: string,\n sessionId?: string,\n ): AsyncIterable<A2ATaskState> {\n const task: A2ATask = {\n id: `task-${Date.now()}`,\n sessionId,\n message: { role: 'user', parts: [{ type: 'text', text: input }] },\n };\n\n const rpcReq: JsonRpcRequest = {\n jsonrpc: '2.0',\n id: _idCounter++,\n method: 'tasks/sendSubscribe',\n params: task,\n };\n\n const res = await fetch(this.baseUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(rpcReq),\n });\n\n if (!res.ok || !res.body) {\n throw new Error(`A2A stream request failed: ${res.status}`);\n }\n\n const reader = res.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (!line.startsWith('data: ')) continue;\n try {\n const rpcRes = JSON.parse(line.slice(6)) as JsonRpcResponse;\n if (rpcRes.error) {\n throw new Error(`A2A error ${rpcRes.error.code}: ${rpcRes.error.message}`);\n }\n if (rpcRes.result) {\n yield rpcRes.result as A2ATaskState;\n }\n } catch (e) {\n if ((e as Error).message.includes('A2A error')) throw e;\n // Skip malformed SSE lines\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@orka-js/a2a",
3
+ "version": "1.5.0",
4
+ "description": "Google A2A (Agent-to-Agent) protocol implementation for OrkaJS",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs",
13
+ "types": "./dist/index.d.ts"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "dependencies": {
20
+ "@orka-js/core": "1.5.0",
21
+ "@orka-js/agent": "1.5.2"
22
+ },
23
+ "peerDependencies": {
24
+ "express": ">=4.0.0"
25
+ },
26
+ "peerDependenciesMeta": {
27
+ "express": {
28
+ "optional": true
29
+ }
30
+ },
31
+ "devDependencies": {
32
+ "@types/express": "^4.17.21",
33
+ "vitest": "^1.6.0"
34
+ },
35
+ "scripts": {
36
+ "build": "tsup",
37
+ "dev": "tsup --watch",
38
+ "typecheck": "tsc --noEmit",
39
+ "test": "vitest run"
40
+ }
41
+ }