opc-agent 2.0.0 → 2.0.2

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.
Files changed (157) hide show
  1. package/README.md +545 -365
  2. package/dist/channels/email.d.ts +32 -26
  3. package/dist/channels/email.js +239 -62
  4. package/dist/channels/feishu.d.ts +21 -6
  5. package/dist/channels/feishu.js +225 -126
  6. package/dist/channels/websocket.d.ts +46 -3
  7. package/dist/channels/websocket.js +306 -37
  8. package/dist/channels/wechat.d.ts +33 -13
  9. package/dist/channels/wechat.js +229 -42
  10. package/dist/cli.js +712 -11
  11. package/dist/core/a2a.d.ts +17 -0
  12. package/dist/core/a2a.js +43 -1
  13. package/dist/core/agent.d.ts +16 -0
  14. package/dist/core/agent.js +108 -0
  15. package/dist/core/runtime.d.ts +6 -0
  16. package/dist/core/runtime.js +161 -2
  17. package/dist/core/sandbox.d.ts +26 -0
  18. package/dist/core/sandbox.js +117 -0
  19. package/dist/core/workflow-graph.d.ts +93 -0
  20. package/dist/core/workflow-graph.js +247 -0
  21. package/dist/doctor.d.ts +15 -0
  22. package/dist/doctor.js +183 -0
  23. package/dist/eval/index.d.ts +65 -0
  24. package/dist/eval/index.js +191 -0
  25. package/dist/index.d.ts +32 -6
  26. package/dist/index.js +63 -4
  27. package/dist/plugins/content-filter.d.ts +7 -0
  28. package/dist/plugins/content-filter.js +25 -0
  29. package/dist/plugins/index.d.ts +42 -0
  30. package/dist/plugins/index.js +108 -2
  31. package/dist/plugins/logger.d.ts +6 -0
  32. package/dist/plugins/logger.js +20 -0
  33. package/dist/plugins/rate-limiter.d.ts +7 -0
  34. package/dist/plugins/rate-limiter.js +35 -0
  35. package/dist/protocols/a2a/client.d.ts +25 -0
  36. package/dist/protocols/a2a/client.js +115 -0
  37. package/dist/protocols/a2a/index.d.ts +6 -0
  38. package/dist/protocols/a2a/index.js +12 -0
  39. package/dist/protocols/a2a/server.d.ts +41 -0
  40. package/dist/protocols/a2a/server.js +295 -0
  41. package/dist/protocols/a2a/types.d.ts +91 -0
  42. package/dist/protocols/a2a/types.js +15 -0
  43. package/dist/protocols/a2a/utils.d.ts +6 -0
  44. package/dist/protocols/a2a/utils.js +47 -0
  45. package/dist/protocols/agui/client.d.ts +10 -0
  46. package/dist/protocols/agui/client.js +75 -0
  47. package/dist/protocols/agui/index.d.ts +4 -0
  48. package/dist/protocols/agui/index.js +25 -0
  49. package/dist/protocols/agui/server.d.ts +37 -0
  50. package/dist/protocols/agui/server.js +191 -0
  51. package/dist/protocols/agui/types.d.ts +107 -0
  52. package/dist/protocols/agui/types.js +17 -0
  53. package/dist/protocols/index.d.ts +2 -0
  54. package/dist/protocols/index.js +19 -0
  55. package/dist/protocols/mcp/agent-tools.d.ts +11 -0
  56. package/dist/protocols/mcp/agent-tools.js +129 -0
  57. package/dist/protocols/mcp/index.d.ts +5 -0
  58. package/dist/protocols/mcp/index.js +11 -0
  59. package/dist/protocols/mcp/server.d.ts +31 -0
  60. package/dist/protocols/mcp/server.js +248 -0
  61. package/dist/protocols/mcp/types.d.ts +92 -0
  62. package/dist/protocols/mcp/types.js +17 -0
  63. package/dist/publish/index.d.ts +45 -0
  64. package/dist/publish/index.js +350 -0
  65. package/dist/schema/oad.d.ts +682 -65
  66. package/dist/schema/oad.js +36 -3
  67. package/dist/security/approval.d.ts +36 -0
  68. package/dist/security/approval.js +113 -0
  69. package/dist/security/index.d.ts +4 -0
  70. package/dist/security/index.js +8 -0
  71. package/dist/security/keys.d.ts +16 -0
  72. package/dist/security/keys.js +117 -0
  73. package/dist/studio/server.d.ts +63 -0
  74. package/dist/studio/server.js +625 -0
  75. package/dist/studio-ui/index.html +662 -0
  76. package/dist/telemetry/index.d.ts +93 -0
  77. package/dist/telemetry/index.js +285 -0
  78. package/package.json +5 -3
  79. package/scripts/install.ps1 +31 -0
  80. package/scripts/install.sh +40 -0
  81. package/src/channels/email.ts +351 -177
  82. package/src/channels/feishu.ts +349 -236
  83. package/src/channels/websocket.ts +399 -87
  84. package/src/channels/wechat.ts +329 -149
  85. package/src/cli.ts +783 -12
  86. package/src/core/a2a.ts +60 -0
  87. package/src/core/agent.ts +125 -0
  88. package/src/core/runtime.ts +127 -0
  89. package/src/core/sandbox.ts +143 -0
  90. package/src/core/workflow-graph.ts +365 -0
  91. package/src/doctor.ts +156 -0
  92. package/src/eval/index.ts +211 -0
  93. package/src/eval/suites/basic.json +16 -0
  94. package/src/eval/suites/memory.json +12 -0
  95. package/src/eval/suites/safety.json +14 -0
  96. package/src/index.ts +58 -6
  97. package/src/plugins/content-filter.ts +23 -0
  98. package/src/plugins/index.ts +133 -2
  99. package/src/plugins/logger.ts +18 -0
  100. package/src/plugins/rate-limiter.ts +38 -0
  101. package/src/protocols/a2a/client.ts +132 -0
  102. package/src/protocols/a2a/index.ts +8 -0
  103. package/src/protocols/a2a/server.ts +333 -0
  104. package/src/protocols/a2a/types.ts +88 -0
  105. package/src/protocols/a2a/utils.ts +50 -0
  106. package/src/protocols/agui/client.ts +83 -0
  107. package/src/protocols/agui/index.ts +4 -0
  108. package/src/protocols/agui/server.ts +218 -0
  109. package/src/protocols/agui/types.ts +153 -0
  110. package/src/protocols/index.ts +2 -0
  111. package/src/protocols/mcp/agent-tools.ts +134 -0
  112. package/src/protocols/mcp/index.ts +8 -0
  113. package/src/protocols/mcp/server.ts +262 -0
  114. package/src/protocols/mcp/types.ts +69 -0
  115. package/src/publish/index.ts +376 -0
  116. package/src/schema/oad.ts +39 -2
  117. package/src/security/approval.ts +131 -0
  118. package/src/security/index.ts +3 -0
  119. package/src/security/keys.ts +87 -0
  120. package/src/studio/server.ts +629 -0
  121. package/src/studio-ui/index.html +662 -0
  122. package/src/telemetry/index.ts +324 -0
  123. package/src/types/agent-workstation.d.ts +2 -0
  124. package/tests/a2a-protocol.test.ts +285 -0
  125. package/tests/agui-protocol.test.ts +246 -0
  126. package/tests/channels/discord.test.ts +79 -0
  127. package/tests/channels/email.test.ts +148 -0
  128. package/tests/channels/feishu.test.ts +123 -0
  129. package/tests/channels/telegram.test.ts +129 -0
  130. package/tests/channels/websocket.test.ts +53 -0
  131. package/tests/channels/wechat.test.ts +170 -0
  132. package/tests/chat-cli.test.ts +160 -0
  133. package/tests/daemon.test.ts +135 -0
  134. package/tests/deepbrain-wire.test.ts +234 -0
  135. package/tests/doctor.test.ts +38 -0
  136. package/tests/eval.test.ts +173 -0
  137. package/tests/init-role.test.ts +124 -0
  138. package/tests/mcp-client.test.ts +92 -0
  139. package/tests/mcp-server.test.ts +178 -0
  140. package/tests/plugin-a2a-enhanced.test.ts +230 -0
  141. package/tests/publish.test.ts +231 -0
  142. package/tests/scheduler.test.ts +200 -0
  143. package/tests/security-enhanced.test.ts +233 -0
  144. package/tests/skill-learner.test.ts +161 -0
  145. package/tests/studio.test.ts +229 -0
  146. package/tests/subagent.test.ts +63 -0
  147. package/tests/telemetry.test.ts +186 -0
  148. package/tests/tools/builtin-extended.test.ts +138 -0
  149. package/tests/workflow-graph.test.ts +279 -0
  150. package/tutorial/customer-service-agent/README.md +612 -0
  151. package/tutorial/customer-service-agent/SOUL.md +26 -0
  152. package/tutorial/customer-service-agent/agent.yaml +63 -0
  153. package/tutorial/customer-service-agent/package.json +19 -0
  154. package/tutorial/customer-service-agent/src/index.ts +69 -0
  155. package/tutorial/customer-service-agent/src/skills/faq.ts +27 -0
  156. package/tutorial/customer-service-agent/src/skills/ticket.ts +22 -0
  157. package/tutorial/customer-service-agent/tsconfig.json +14 -0
@@ -0,0 +1,324 @@
1
+ /**
2
+ * OPC Agent Telemetry — Lightweight OTel-compatible tracing & metrics.
3
+ * Zero external dependencies. Produces OTLP-compatible JSON.
4
+ */
5
+
6
+ import * as fs from 'fs';
7
+ import * as crypto from 'crypto';
8
+
9
+ // ─── Types ───────────────────────────────────────────────────
10
+
11
+ export interface Span {
12
+ traceId: string;
13
+ spanId: string;
14
+ parentSpanId?: string;
15
+ name: string;
16
+ kind: 'internal' | 'client' | 'server';
17
+ startTime: number; // epoch ms
18
+ endTime?: number;
19
+ status: 'ok' | 'error' | 'unset';
20
+ attributes: Record<string, string | number | boolean>;
21
+ events: SpanEvent[];
22
+ }
23
+
24
+ export interface SpanEvent {
25
+ name: string;
26
+ timestamp: number;
27
+ attributes?: Record<string, string | number | boolean>;
28
+ }
29
+
30
+ export interface Metric {
31
+ name: string;
32
+ type: 'counter' | 'gauge' | 'histogram';
33
+ value: number;
34
+ timestamp: number;
35
+ labels: Record<string, string>;
36
+ }
37
+
38
+ export interface TraceExporter {
39
+ export(spans: Span[]): Promise<void>;
40
+ }
41
+
42
+ // ─── ID Generation ───────────────────────────────────────────
43
+
44
+ export function generateTraceId(): string {
45
+ return crypto.randomBytes(16).toString('hex'); // 32 hex chars
46
+ }
47
+
48
+ export function generateSpanId(): string {
49
+ return crypto.randomBytes(8).toString('hex'); // 16 hex chars
50
+ }
51
+
52
+ // ─── Tracer ──────────────────────────────────────────────────
53
+
54
+ export class Tracer {
55
+ private spans: Span[] = [];
56
+ private metrics: Metric[] = [];
57
+ private maxSpans: number;
58
+ private maxMetrics: number;
59
+ private exporters: TraceExporter[] = [];
60
+
61
+ constructor(options?: { maxSpans?: number; maxMetrics?: number }) {
62
+ this.maxSpans = options?.maxSpans || 10000;
63
+ this.maxMetrics = options?.maxMetrics || 50000;
64
+ }
65
+
66
+ startSpan(name: string, options?: {
67
+ parent?: Span;
68
+ attributes?: Record<string, string | number | boolean>;
69
+ kind?: Span['kind'];
70
+ }): Span {
71
+ const span: Span = {
72
+ traceId: options?.parent?.traceId || generateTraceId(),
73
+ spanId: generateSpanId(),
74
+ parentSpanId: options?.parent?.spanId,
75
+ name,
76
+ kind: options?.kind || 'internal',
77
+ startTime: Date.now(),
78
+ status: 'unset',
79
+ attributes: options?.attributes ? { ...options.attributes } : {},
80
+ events: [],
81
+ };
82
+ this.spans.push(span);
83
+
84
+ // Evict oldest spans if over limit
85
+ if (this.spans.length > this.maxSpans) {
86
+ const excess = this.spans.length - this.maxSpans;
87
+ this.spans.splice(0, excess);
88
+ }
89
+
90
+ return span;
91
+ }
92
+
93
+ endSpan(span: Span, status?: Span['status']): void {
94
+ span.endTime = Date.now();
95
+ span.status = status || 'ok';
96
+
97
+ // Notify exporters
98
+ for (const exporter of this.exporters) {
99
+ exporter.export([span]).catch(() => {});
100
+ }
101
+ }
102
+
103
+ addEvent(span: Span, name: string, attributes?: Record<string, string | number | boolean>): void {
104
+ span.events.push({ name, timestamp: Date.now(), attributes });
105
+ }
106
+
107
+ // ─── Metrics ─────────────────────────────────────────────
108
+
109
+ increment(name: string, value: number = 1, labels: Record<string, string> = {}): void {
110
+ this.addMetric(name, 'counter', value, labels);
111
+ }
112
+
113
+ gauge(name: string, value: number, labels: Record<string, string> = {}): void {
114
+ this.addMetric(name, 'gauge', value, labels);
115
+ }
116
+
117
+ histogram(name: string, value: number, labels: Record<string, string> = {}): void {
118
+ this.addMetric(name, 'histogram', value, labels);
119
+ }
120
+
121
+ private addMetric(name: string, type: Metric['type'], value: number, labels: Record<string, string>): void {
122
+ this.metrics.push({ name, type, value, timestamp: Date.now(), labels });
123
+ if (this.metrics.length > this.maxMetrics) {
124
+ this.metrics.splice(0, this.metrics.length - this.maxMetrics);
125
+ }
126
+ }
127
+
128
+ // ─── Query ───────────────────────────────────────────────
129
+
130
+ getSpans(options?: { limit?: number; traceId?: string; name?: string; since?: number }): Span[] {
131
+ let result = [...this.spans];
132
+
133
+ if (options?.traceId) result = result.filter(s => s.traceId === options.traceId);
134
+ if (options?.name) result = result.filter(s => s.name === options.name);
135
+ if (options?.since) result = result.filter(s => s.startTime >= options.since!);
136
+
137
+ // Most recent first
138
+ result.sort((a, b) => b.startTime - a.startTime);
139
+
140
+ if (options?.limit) result = result.slice(0, options.limit);
141
+ return result;
142
+ }
143
+
144
+ getMetrics(options?: { name?: string; since?: number }): Metric[] {
145
+ let result = [...this.metrics];
146
+ if (options?.name) result = result.filter(m => m.name === options.name);
147
+ if (options?.since) result = result.filter(m => m.timestamp >= options.since!);
148
+ return result;
149
+ }
150
+
151
+ getTrace(traceId: string): Span[] {
152
+ return this.spans.filter(s => s.traceId === traceId).sort((a, b) => a.startTime - b.startTime);
153
+ }
154
+
155
+ // ─── Export (OTLP-compatible) ────────────────────────────
156
+
157
+ addExporter(exporter: TraceExporter): void {
158
+ this.exporters.push(exporter);
159
+ }
160
+
161
+ exportOTLP(): object {
162
+ // OTLP JSON format: https://opentelemetry.io/docs/specs/otlp/
163
+ const spansByResource = this.spans.filter(s => s.endTime != null);
164
+
165
+ return {
166
+ resourceSpans: [{
167
+ resource: {
168
+ attributes: [
169
+ { key: 'service.name', value: { stringValue: 'opc-agent' } },
170
+ ],
171
+ },
172
+ scopeSpans: [{
173
+ scope: { name: 'opc-telemetry', version: '1.0.0' },
174
+ spans: spansByResource.map(s => ({
175
+ traceId: s.traceId,
176
+ spanId: s.spanId,
177
+ parentSpanId: s.parentSpanId || '',
178
+ name: s.name,
179
+ kind: s.kind === 'server' ? 2 : s.kind === 'client' ? 3 : 1,
180
+ startTimeUnixNano: String(s.startTime * 1_000_000),
181
+ endTimeUnixNano: String((s.endTime || s.startTime) * 1_000_000),
182
+ attributes: Object.entries(s.attributes).map(([key, value]) => ({
183
+ key,
184
+ value: typeof value === 'string' ? { stringValue: value }
185
+ : typeof value === 'number' ? (Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value })
186
+ : { boolValue: value },
187
+ })),
188
+ events: s.events.map(e => ({
189
+ timeUnixNano: String(e.timestamp * 1_000_000),
190
+ name: e.name,
191
+ attributes: e.attributes ? Object.entries(e.attributes).map(([key, value]) => ({
192
+ key,
193
+ value: typeof value === 'string' ? { stringValue: value }
194
+ : typeof value === 'number' ? { intValue: String(value) }
195
+ : { boolValue: value },
196
+ })) : [],
197
+ })),
198
+ status: {
199
+ code: s.status === 'ok' ? 1 : s.status === 'error' ? 2 : 0,
200
+ },
201
+ })),
202
+ }],
203
+ }],
204
+ };
205
+ }
206
+
207
+ // ─── Stats ───────────────────────────────────────────────
208
+
209
+ getStats(): {
210
+ totalSpans: number;
211
+ totalTraces: number;
212
+ avgDuration: number;
213
+ errorRate: number;
214
+ spansByName: Record<string, number>;
215
+ p50Latency: number;
216
+ p95Latency: number;
217
+ p99Latency: number;
218
+ } {
219
+ const completed = this.spans.filter(s => s.endTime != null);
220
+ const durations = completed.map(s => s.endTime! - s.startTime).sort((a, b) => a - b);
221
+ const traceIds = new Set(this.spans.map(s => s.traceId));
222
+ const errors = completed.filter(s => s.status === 'error').length;
223
+
224
+ const spansByName: Record<string, number> = {};
225
+ for (const s of this.spans) {
226
+ spansByName[s.name] = (spansByName[s.name] || 0) + 1;
227
+ }
228
+
229
+ const percentile = (arr: number[], p: number): number => {
230
+ if (arr.length === 0) return 0;
231
+ const idx = Math.ceil(arr.length * p / 100) - 1;
232
+ return arr[Math.max(0, idx)];
233
+ };
234
+
235
+ return {
236
+ totalSpans: this.spans.length,
237
+ totalTraces: traceIds.size,
238
+ avgDuration: durations.length > 0 ? durations.reduce((a, b) => a + b, 0) / durations.length : 0,
239
+ errorRate: completed.length > 0 ? errors / completed.length : 0,
240
+ spansByName,
241
+ p50Latency: percentile(durations, 50),
242
+ p95Latency: percentile(durations, 95),
243
+ p99Latency: percentile(durations, 99),
244
+ };
245
+ }
246
+
247
+ clear(): void {
248
+ this.spans = [];
249
+ this.metrics = [];
250
+ }
251
+ }
252
+
253
+ // ─── Exporters ───────────────────────────────────────────────
254
+
255
+ export class ConsoleExporter implements TraceExporter {
256
+ async export(spans: Span[]): Promise<void> {
257
+ for (const span of spans) {
258
+ const duration = span.endTime ? `${span.endTime - span.startTime}ms` : 'ongoing';
259
+ console.log(`[TRACE] ${span.name} (${duration}) [${span.status}] trace=${span.traceId.slice(0, 8)}`);
260
+ }
261
+ }
262
+ }
263
+
264
+ export class FileExporter implements TraceExporter {
265
+ private filePath: string;
266
+
267
+ constructor(filePath: string) {
268
+ this.filePath = filePath;
269
+ }
270
+
271
+ async export(spans: Span[]): Promise<void> {
272
+ const lines = spans.map(s => JSON.stringify(s)).join('\n') + '\n';
273
+ fs.appendFileSync(this.filePath, lines);
274
+ }
275
+ }
276
+
277
+ export class OTLPHttpExporter implements TraceExporter {
278
+ private endpoint: string;
279
+
280
+ constructor(endpoint: string) {
281
+ this.endpoint = endpoint.replace(/\/$/, '');
282
+ }
283
+
284
+ async export(spans: Span[]): Promise<void> {
285
+ const body = {
286
+ resourceSpans: [{
287
+ resource: {
288
+ attributes: [
289
+ { key: 'service.name', value: { stringValue: 'opc-agent' } },
290
+ ],
291
+ },
292
+ scopeSpans: [{
293
+ scope: { name: 'opc-telemetry', version: '1.0.0' },
294
+ spans: spans.filter(s => s.endTime).map(s => ({
295
+ traceId: s.traceId,
296
+ spanId: s.spanId,
297
+ parentSpanId: s.parentSpanId || '',
298
+ name: s.name,
299
+ kind: s.kind === 'server' ? 2 : s.kind === 'client' ? 3 : 1,
300
+ startTimeUnixNano: String(s.startTime * 1_000_000),
301
+ endTimeUnixNano: String((s.endTime || s.startTime) * 1_000_000),
302
+ attributes: Object.entries(s.attributes).map(([key, value]) => ({
303
+ key,
304
+ value: typeof value === 'string' ? { stringValue: value }
305
+ : typeof value === 'number' ? { intValue: String(value) }
306
+ : { boolValue: value },
307
+ })),
308
+ status: { code: s.status === 'ok' ? 1 : s.status === 'error' ? 2 : 0 },
309
+ })),
310
+ }],
311
+ }],
312
+ };
313
+
314
+ try {
315
+ await fetch(`${this.endpoint}/v1/traces`, {
316
+ method: 'POST',
317
+ headers: { 'Content-Type': 'application/json' },
318
+ body: JSON.stringify(body),
319
+ });
320
+ } catch {
321
+ // Best effort
322
+ }
323
+ }
324
+ }
@@ -0,0 +1,2 @@
1
+ declare module "agent-workstation";
2
+ declare module "deepbrain";
@@ -0,0 +1,285 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
+ import { A2AServer } from '../src/protocols/a2a/server';
3
+ import { A2AClient } from '../src/protocols/a2a/client';
4
+ import { oadToAgentCard } from '../src/protocols/a2a/utils';
5
+ import { JSON_RPC_ERRORS } from '../src/protocols/a2a/types';
6
+ import type { A2AAgentCard, A2ATask, A2AMessage } from '../src/protocols/a2a/types';
7
+
8
+ // Mock agent
9
+ function createMockAgent(name = 'test-agent') {
10
+ return {
11
+ name,
12
+ config: { systemPrompt: 'I am a test agent' },
13
+ handleMessage: async (msg: any) => ({ content: `Echo: ${msg.content}`, role: 'assistant' }),
14
+ };
15
+ }
16
+
17
+ describe('oadToAgentCard', () => {
18
+ it('should generate card from OAD', () => {
19
+ const oad = {
20
+ metadata: { name: 'my-agent', description: 'A test agent', version: '2.0.0' },
21
+ spec: {
22
+ skills: [
23
+ { id: 'sum', name: 'Summarize', description: 'Summarize text', tags: ['nlp'] },
24
+ ],
25
+ channels: [{ type: 'websocket' }],
26
+ },
27
+ };
28
+ const card = oadToAgentCard(oad, 'http://localhost:3001');
29
+ expect(card.name).toBe('my-agent');
30
+ expect(card.description).toBe('A test agent');
31
+ expect(card.version).toBe('2.0.0');
32
+ expect(card.url).toBe('http://localhost:3001');
33
+ expect(card.skills).toHaveLength(1);
34
+ expect(card.skills[0].id).toBe('sum');
35
+ expect(card.capabilities.streaming).toBe(true);
36
+ });
37
+
38
+ it('should create default skill when none defined', () => {
39
+ const oad = { metadata: { name: 'basic', description: 'Basic agent' }, spec: {} };
40
+ const card = oadToAgentCard(oad, 'http://localhost:3001');
41
+ expect(card.skills).toHaveLength(1);
42
+ expect(card.skills[0].id).toBe('default');
43
+ });
44
+
45
+ it('should handle empty OAD', () => {
46
+ const card = oadToAgentCard({}, 'http://localhost:3001');
47
+ expect(card.name).toBe('opc-agent');
48
+ expect(card.url).toBe('http://localhost:3001');
49
+ });
50
+
51
+ it('should strip trailing slash from URL', () => {
52
+ const card = oadToAgentCard({}, 'http://localhost:3001/');
53
+ expect(card.url).toBe('http://localhost:3001');
54
+ });
55
+ });
56
+
57
+ describe('A2AServer', () => {
58
+ let server: A2AServer;
59
+ const PORT = 39871;
60
+
61
+ beforeEach(async () => {
62
+ const agent = createMockAgent();
63
+ server = new A2AServer(agent, {
64
+ card: { name: 'test-server', description: 'Test', url: `http://localhost:${PORT}` },
65
+ });
66
+ await server.start(PORT);
67
+ });
68
+
69
+ afterEach(async () => {
70
+ await server.stop();
71
+ });
72
+
73
+ it('should serve /.well-known/agent.json', async () => {
74
+ const res = await fetch(`http://localhost:${PORT}/.well-known/agent.json`);
75
+ expect(res.status).toBe(200);
76
+ const card: A2AAgentCard = await res.json() as any;
77
+ expect(card.name).toBe('test-server');
78
+ });
79
+
80
+ it('should handle tasks/send', async () => {
81
+ const res = await fetch(`http://localhost:${PORT}`, {
82
+ method: 'POST',
83
+ headers: { 'Content-Type': 'application/json' },
84
+ body: JSON.stringify({
85
+ jsonrpc: '2.0', id: '1', method: 'tasks/send',
86
+ params: { id: 'task-1', message: { role: 'user', parts: [{ type: 'text', text: 'Hello' }] } },
87
+ }),
88
+ });
89
+ const json = await res.json() as any;
90
+ expect(json.result.id).toBe('task-1');
91
+ expect(json.result.status.state).toBe('completed');
92
+ expect(json.result.history).toHaveLength(2); // user + agent
93
+ });
94
+
95
+ it('should handle tasks/get', async () => {
96
+ // First create a task
97
+ await fetch(`http://localhost:${PORT}`, {
98
+ method: 'POST',
99
+ headers: { 'Content-Type': 'application/json' },
100
+ body: JSON.stringify({
101
+ jsonrpc: '2.0', id: '1', method: 'tasks/send',
102
+ params: { id: 'task-get-1', message: { role: 'user', parts: [{ type: 'text', text: 'Hi' }] } },
103
+ }),
104
+ });
105
+
106
+ // Then get it
107
+ const res = await fetch(`http://localhost:${PORT}`, {
108
+ method: 'POST',
109
+ headers: { 'Content-Type': 'application/json' },
110
+ body: JSON.stringify({ jsonrpc: '2.0', id: '2', method: 'tasks/get', params: { id: 'task-get-1' } }),
111
+ });
112
+ const json = await res.json() as any;
113
+ expect(json.result.id).toBe('task-get-1');
114
+ expect(json.result.status.state).toBe('completed');
115
+ });
116
+
117
+ it('should handle tasks/cancel', async () => {
118
+ // Create task
119
+ await fetch(`http://localhost:${PORT}`, {
120
+ method: 'POST',
121
+ headers: { 'Content-Type': 'application/json' },
122
+ body: JSON.stringify({
123
+ jsonrpc: '2.0', id: '1', method: 'tasks/send',
124
+ params: { id: 'task-cancel-1', message: { role: 'user', parts: [{ type: 'text', text: 'Hi' }] } },
125
+ }),
126
+ });
127
+
128
+ const res = await fetch(`http://localhost:${PORT}`, {
129
+ method: 'POST',
130
+ headers: { 'Content-Type': 'application/json' },
131
+ body: JSON.stringify({ jsonrpc: '2.0', id: '2', method: 'tasks/cancel', params: { id: 'task-cancel-1' } }),
132
+ });
133
+ const json = await res.json() as any;
134
+ expect(json.result.status.state).toBe('canceled');
135
+ });
136
+
137
+ it('should return error for unknown task', async () => {
138
+ const res = await fetch(`http://localhost:${PORT}`, {
139
+ method: 'POST',
140
+ headers: { 'Content-Type': 'application/json' },
141
+ body: JSON.stringify({ jsonrpc: '2.0', id: '1', method: 'tasks/get', params: { id: 'nonexistent' } }),
142
+ });
143
+ const json = await res.json() as any;
144
+ expect(json.error).toBeDefined();
145
+ expect(json.error.code).toBe(JSON_RPC_ERRORS.TASK_NOT_FOUND);
146
+ });
147
+
148
+ it('should return error for unknown method', async () => {
149
+ const res = await fetch(`http://localhost:${PORT}`, {
150
+ method: 'POST',
151
+ headers: { 'Content-Type': 'application/json' },
152
+ body: JSON.stringify({ jsonrpc: '2.0', id: '1', method: 'unknown/method', params: {} }),
153
+ });
154
+ const json = await res.json() as any;
155
+ expect(json.error).toBeDefined();
156
+ expect(json.error.code).toBe(JSON_RPC_ERRORS.METHOD_NOT_FOUND);
157
+ });
158
+
159
+ it('should return parse error for invalid JSON', async () => {
160
+ const res = await fetch(`http://localhost:${PORT}`, {
161
+ method: 'POST',
162
+ headers: { 'Content-Type': 'application/json' },
163
+ body: 'not json',
164
+ });
165
+ const json = await res.json() as any;
166
+ expect(json.error.code).toBe(JSON_RPC_ERRORS.PARSE_ERROR);
167
+ });
168
+
169
+ it('should return getAgentCard()', () => {
170
+ const card = server.getAgentCard();
171
+ expect(card.name).toBe('test-server');
172
+ expect(card.capabilities).toBeDefined();
173
+ });
174
+ });
175
+
176
+ describe('A2AClient', () => {
177
+ let server: A2AServer;
178
+ let client: A2AClient;
179
+ const PORT = 39872;
180
+
181
+ beforeEach(async () => {
182
+ const agent = createMockAgent();
183
+ server = new A2AServer(agent, {
184
+ card: { name: 'client-test', description: 'Test' },
185
+ });
186
+ await server.start(PORT);
187
+ client = new A2AClient(`http://localhost:${PORT}`);
188
+ });
189
+
190
+ afterEach(async () => {
191
+ await server.stop();
192
+ });
193
+
194
+ it('should getAgentCard', async () => {
195
+ const card = await client.getAgentCard();
196
+ expect(card.name).toBe('client-test');
197
+ });
198
+
199
+ it('should sendText and get response', async () => {
200
+ const response = await client.sendText('Hello agent');
201
+ expect(response).toContain('Echo: Hello agent');
202
+ });
203
+
204
+ it('should sendTask with message', async () => {
205
+ const task = await client.sendTask(
206
+ { role: 'user', parts: [{ type: 'text', text: 'Test message' }] },
207
+ { taskId: 'client-task-1' },
208
+ );
209
+ expect(task.id).toBe('client-task-1');
210
+ expect(task.status.state).toBe('completed');
211
+ });
212
+
213
+ it('should getTask', async () => {
214
+ await client.sendText('setup', { taskId: 'get-test' });
215
+ const task = await client.getTask('get-test');
216
+ expect(task.id).toBe('get-test');
217
+ });
218
+
219
+ it('should cancelTask', async () => {
220
+ await client.sendText('setup', { taskId: 'cancel-test' });
221
+ const task = await client.cancelTask('cancel-test');
222
+ expect(task.status.state).toBe('canceled');
223
+ });
224
+ });
225
+
226
+ describe('Task state transitions', () => {
227
+ it('should track state transitions through task lifecycle', async () => {
228
+ const states: string[] = [];
229
+ const agent = createMockAgent();
230
+ const server = new A2AServer(agent);
231
+
232
+ server.onTask(async (task) => {
233
+ states.push(task.status.state);
234
+ task.status = { state: 'working', timestamp: new Date().toISOString() };
235
+ states.push('working');
236
+ task.status = { state: 'completed', timestamp: new Date().toISOString() };
237
+ states.push('completed');
238
+ return task;
239
+ });
240
+
241
+ const PORT = 39873;
242
+ await server.start(PORT);
243
+
244
+ const client = new A2AClient(`http://localhost:${PORT}`);
245
+ await client.sendText('test');
246
+
247
+ expect(states).toContain('working');
248
+ expect(states).toContain('completed');
249
+
250
+ await server.stop();
251
+ });
252
+ });
253
+
254
+ describe('Message part types', () => {
255
+ it('should handle text parts', async () => {
256
+ const server = new A2AServer(createMockAgent());
257
+ const PORT = 39874;
258
+ await server.start(PORT);
259
+
260
+ const msg: A2AMessage = { role: 'user', parts: [{ type: 'text', text: 'hello' }] };
261
+ const client = new A2AClient(`http://localhost:${PORT}`);
262
+ const task = await client.sendTask(msg);
263
+ expect(task.history[0].parts[0].type).toBe('text');
264
+
265
+ await server.stop();
266
+ });
267
+
268
+ it('should handle file parts in message', () => {
269
+ const msg: A2AMessage = {
270
+ role: 'user',
271
+ parts: [{ type: 'file', file: { name: 'test.txt', mimeType: 'text/plain', bytes: 'aGVsbG8=' } }],
272
+ };
273
+ expect(msg.parts[0].type).toBe('file');
274
+ expect((msg.parts[0] as any).file.name).toBe('test.txt');
275
+ });
276
+
277
+ it('should handle data parts in message', () => {
278
+ const msg: A2AMessage = {
279
+ role: 'user',
280
+ parts: [{ type: 'data', data: { key: 'value', count: 42 } }],
281
+ };
282
+ expect(msg.parts[0].type).toBe('data');
283
+ expect((msg.parts[0] as any).data.key).toBe('value');
284
+ });
285
+ });