opc-agent 1.4.0 → 2.0.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.
Files changed (198) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +91 -32
  3. package/dist/channels/email.d.ts +32 -26
  4. package/dist/channels/email.js +239 -62
  5. package/dist/channels/feishu.d.ts +21 -6
  6. package/dist/channels/feishu.js +225 -126
  7. package/dist/channels/telegram.d.ts +30 -9
  8. package/dist/channels/telegram.js +125 -33
  9. package/dist/channels/websocket.d.ts +46 -3
  10. package/dist/channels/websocket.js +306 -37
  11. package/dist/channels/wechat.d.ts +33 -13
  12. package/dist/channels/wechat.js +229 -42
  13. package/dist/cli.js +1127 -19
  14. package/dist/core/a2a.d.ts +17 -0
  15. package/dist/core/a2a.js +43 -1
  16. package/dist/core/agent.d.ts +39 -0
  17. package/dist/core/agent.js +228 -3
  18. package/dist/core/runtime.d.ts +7 -0
  19. package/dist/core/runtime.js +205 -2
  20. package/dist/core/sandbox.d.ts +26 -0
  21. package/dist/core/sandbox.js +117 -0
  22. package/dist/core/scheduler.d.ts +52 -0
  23. package/dist/core/scheduler.js +168 -0
  24. package/dist/core/subagent.d.ts +28 -0
  25. package/dist/core/subagent.js +65 -0
  26. package/dist/core/workflow-graph.d.ts +93 -0
  27. package/dist/core/workflow-graph.js +247 -0
  28. package/dist/daemon.d.ts +3 -0
  29. package/dist/daemon.js +134 -0
  30. package/dist/doctor.d.ts +15 -0
  31. package/dist/doctor.js +183 -0
  32. package/dist/eval/index.d.ts +65 -0
  33. package/dist/eval/index.js +191 -0
  34. package/dist/index.d.ts +37 -6
  35. package/dist/index.js +75 -3
  36. package/dist/plugins/content-filter.d.ts +7 -0
  37. package/dist/plugins/content-filter.js +25 -0
  38. package/dist/plugins/index.d.ts +42 -0
  39. package/dist/plugins/index.js +108 -2
  40. package/dist/plugins/logger.d.ts +6 -0
  41. package/dist/plugins/logger.js +20 -0
  42. package/dist/plugins/rate-limiter.d.ts +7 -0
  43. package/dist/plugins/rate-limiter.js +35 -0
  44. package/dist/protocols/a2a/client.d.ts +25 -0
  45. package/dist/protocols/a2a/client.js +115 -0
  46. package/dist/protocols/a2a/index.d.ts +6 -0
  47. package/dist/protocols/a2a/index.js +12 -0
  48. package/dist/protocols/a2a/server.d.ts +41 -0
  49. package/dist/protocols/a2a/server.js +295 -0
  50. package/dist/protocols/a2a/types.d.ts +91 -0
  51. package/dist/protocols/a2a/types.js +15 -0
  52. package/dist/protocols/a2a/utils.d.ts +6 -0
  53. package/dist/protocols/a2a/utils.js +47 -0
  54. package/dist/protocols/agui/client.d.ts +10 -0
  55. package/dist/protocols/agui/client.js +75 -0
  56. package/dist/protocols/agui/index.d.ts +4 -0
  57. package/dist/protocols/agui/index.js +25 -0
  58. package/dist/protocols/agui/server.d.ts +37 -0
  59. package/dist/protocols/agui/server.js +191 -0
  60. package/dist/protocols/agui/types.d.ts +107 -0
  61. package/dist/protocols/agui/types.js +17 -0
  62. package/dist/protocols/index.d.ts +2 -0
  63. package/dist/protocols/index.js +19 -0
  64. package/dist/protocols/mcp/agent-tools.d.ts +11 -0
  65. package/dist/protocols/mcp/agent-tools.js +129 -0
  66. package/dist/protocols/mcp/index.d.ts +5 -0
  67. package/dist/protocols/mcp/index.js +11 -0
  68. package/dist/protocols/mcp/server.d.ts +31 -0
  69. package/dist/protocols/mcp/server.js +248 -0
  70. package/dist/protocols/mcp/types.d.ts +92 -0
  71. package/dist/protocols/mcp/types.js +17 -0
  72. package/dist/providers/index.d.ts +5 -1
  73. package/dist/providers/index.js +16 -9
  74. package/dist/publish/index.d.ts +45 -0
  75. package/dist/publish/index.js +350 -0
  76. package/dist/schema/oad.d.ts +859 -67
  77. package/dist/schema/oad.js +47 -3
  78. package/dist/security/approval.d.ts +36 -0
  79. package/dist/security/approval.js +113 -0
  80. package/dist/security/index.d.ts +4 -0
  81. package/dist/security/index.js +8 -0
  82. package/dist/security/keys.d.ts +16 -0
  83. package/dist/security/keys.js +117 -0
  84. package/dist/skills/auto-learn.d.ts +28 -0
  85. package/dist/skills/auto-learn.js +257 -0
  86. package/dist/studio/server.d.ts +63 -0
  87. package/dist/studio/server.js +625 -0
  88. package/dist/studio-ui/index.html +662 -0
  89. package/dist/telemetry/index.d.ts +93 -0
  90. package/dist/telemetry/index.js +285 -0
  91. package/dist/tools/builtin/datetime.d.ts +3 -0
  92. package/dist/tools/builtin/datetime.js +44 -0
  93. package/dist/tools/builtin/file.d.ts +3 -0
  94. package/dist/tools/builtin/file.js +151 -0
  95. package/dist/tools/builtin/index.d.ts +15 -0
  96. package/dist/tools/builtin/index.js +30 -0
  97. package/dist/tools/builtin/shell.d.ts +3 -0
  98. package/dist/tools/builtin/shell.js +43 -0
  99. package/dist/tools/builtin/web.d.ts +3 -0
  100. package/dist/tools/builtin/web.js +37 -0
  101. package/dist/tools/mcp-client.d.ts +24 -0
  102. package/dist/tools/mcp-client.js +119 -0
  103. package/package.json +5 -3
  104. package/scripts/install.ps1 +31 -0
  105. package/scripts/install.sh +40 -0
  106. package/src/channels/email.ts +351 -177
  107. package/src/channels/feishu.ts +349 -236
  108. package/src/channels/telegram.ts +212 -90
  109. package/src/channels/websocket.ts +399 -87
  110. package/src/channels/wechat.ts +329 -149
  111. package/src/cli.ts +1201 -20
  112. package/src/core/a2a.ts +60 -0
  113. package/src/core/agent.ts +420 -152
  114. package/src/core/runtime.ts +174 -0
  115. package/src/core/sandbox.ts +143 -0
  116. package/src/core/scheduler.ts +187 -0
  117. package/src/core/subagent.ts +98 -0
  118. package/src/core/workflow-graph.ts +365 -0
  119. package/src/daemon.ts +96 -0
  120. package/src/doctor.ts +156 -0
  121. package/src/eval/index.ts +211 -0
  122. package/src/eval/suites/basic.json +16 -0
  123. package/src/eval/suites/memory.json +12 -0
  124. package/src/eval/suites/safety.json +14 -0
  125. package/src/index.ts +65 -6
  126. package/src/plugins/content-filter.ts +23 -0
  127. package/src/plugins/index.ts +133 -2
  128. package/src/plugins/logger.ts +18 -0
  129. package/src/plugins/rate-limiter.ts +38 -0
  130. package/src/protocols/a2a/client.ts +132 -0
  131. package/src/protocols/a2a/index.ts +8 -0
  132. package/src/protocols/a2a/server.ts +333 -0
  133. package/src/protocols/a2a/types.ts +88 -0
  134. package/src/protocols/a2a/utils.ts +50 -0
  135. package/src/protocols/agui/client.ts +83 -0
  136. package/src/protocols/agui/index.ts +4 -0
  137. package/src/protocols/agui/server.ts +218 -0
  138. package/src/protocols/agui/types.ts +153 -0
  139. package/src/protocols/index.ts +2 -0
  140. package/src/protocols/mcp/agent-tools.ts +134 -0
  141. package/src/protocols/mcp/index.ts +8 -0
  142. package/src/protocols/mcp/server.ts +262 -0
  143. package/src/protocols/mcp/types.ts +69 -0
  144. package/src/providers/index.ts +354 -339
  145. package/src/publish/index.ts +376 -0
  146. package/src/schema/oad.ts +204 -154
  147. package/src/security/approval.ts +131 -0
  148. package/src/security/index.ts +3 -0
  149. package/src/security/keys.ts +87 -0
  150. package/src/skills/auto-learn.ts +262 -0
  151. package/src/studio/server.ts +629 -0
  152. package/src/studio-ui/index.html +662 -0
  153. package/src/telemetry/index.ts +324 -0
  154. package/src/tools/builtin/datetime.ts +41 -0
  155. package/src/tools/builtin/file.ts +107 -0
  156. package/src/tools/builtin/index.ts +28 -0
  157. package/src/tools/builtin/shell.ts +43 -0
  158. package/src/tools/builtin/web.ts +35 -0
  159. package/src/tools/mcp-client.ts +131 -0
  160. package/src/types/agent-workstation.d.ts +2 -0
  161. package/tests/a2a-protocol.test.ts +285 -0
  162. package/tests/agui-protocol.test.ts +246 -0
  163. package/tests/auto-learn.test.ts +105 -0
  164. package/tests/builtin-tools.test.ts +83 -0
  165. package/tests/channels/discord.test.ts +79 -0
  166. package/tests/channels/email.test.ts +148 -0
  167. package/tests/channels/feishu.test.ts +123 -0
  168. package/tests/channels/telegram.test.ts +129 -0
  169. package/tests/channels/websocket.test.ts +53 -0
  170. package/tests/channels/wechat.test.ts +170 -0
  171. package/tests/chat-cli.test.ts +160 -0
  172. package/tests/cli.test.ts +46 -0
  173. package/tests/daemon.test.ts +135 -0
  174. package/tests/deepbrain-wire.test.ts +234 -0
  175. package/tests/doctor.test.ts +38 -0
  176. package/tests/eval.test.ts +173 -0
  177. package/tests/init-role.test.ts +124 -0
  178. package/tests/mcp-client.test.ts +92 -0
  179. package/tests/mcp-server.test.ts +178 -0
  180. package/tests/plugin-a2a-enhanced.test.ts +230 -0
  181. package/tests/publish.test.ts +231 -0
  182. package/tests/scheduler.test.ts +200 -0
  183. package/tests/security-enhanced.test.ts +233 -0
  184. package/tests/skill-learner.test.ts +161 -0
  185. package/tests/studio.test.ts +229 -0
  186. package/tests/subagent.test.ts +193 -0
  187. package/tests/telegram-discord.test.ts +60 -0
  188. package/tests/telemetry.test.ts +186 -0
  189. package/tests/tools/builtin-extended.test.ts +138 -0
  190. package/tests/workflow-graph.test.ts +279 -0
  191. package/tutorial/customer-service-agent/README.md +612 -0
  192. package/tutorial/customer-service-agent/SOUL.md +26 -0
  193. package/tutorial/customer-service-agent/agent.yaml +63 -0
  194. package/tutorial/customer-service-agent/package.json +19 -0
  195. package/tutorial/customer-service-agent/src/index.ts +69 -0
  196. package/tutorial/customer-service-agent/src/skills/faq.ts +27 -0
  197. package/tutorial/customer-service-agent/src/skills/ticket.ts +22 -0
  198. package/tutorial/customer-service-agent/tsconfig.json +14 -0
@@ -0,0 +1,131 @@
1
+ import { spawn, type ChildProcess } from 'child_process';
2
+ import type { MCPToolDefinition, MCPToolResult } from './mcp';
3
+
4
+ export interface MCPServerConfig {
5
+ name: string;
6
+ command: string;
7
+ args?: string[];
8
+ env?: Record<string, string>;
9
+ }
10
+
11
+ export class MCPClient {
12
+ private process: ChildProcess | null = null;
13
+ private config: MCPServerConfig | null = null;
14
+ private nextId = 1;
15
+ private pending = new Map<number, { resolve: (v: any) => void; reject: (e: Error) => void }>();
16
+ private buffer = '';
17
+ private connected = false;
18
+
19
+ async connect(config: MCPServerConfig): Promise<void> {
20
+ this.config = config;
21
+ this.process = spawn(config.command, config.args ?? [], {
22
+ stdio: ['pipe', 'pipe', 'pipe'],
23
+ env: { ...process.env, ...config.env },
24
+ });
25
+
26
+ this.process.stdout!.on('data', (data: Buffer) => {
27
+ this.buffer += data.toString();
28
+ this.processBuffer();
29
+ });
30
+
31
+ this.process.on('error', (err) => {
32
+ for (const [, p] of this.pending) p.reject(err);
33
+ this.pending.clear();
34
+ });
35
+
36
+ this.process.on('exit', () => {
37
+ this.connected = false;
38
+ for (const [, p] of this.pending) p.reject(new Error('MCP server exited'));
39
+ this.pending.clear();
40
+ });
41
+
42
+ // Send initialize
43
+ await this.sendRequest('initialize', {
44
+ protocolVersion: '2024-11-05',
45
+ capabilities: {},
46
+ clientInfo: { name: 'opc-agent', version: '0.7.0' },
47
+ });
48
+
49
+ // Send initialized notification
50
+ this.sendNotification('notifications/initialized', {});
51
+ this.connected = true;
52
+ }
53
+
54
+ private processBuffer(): void {
55
+ const lines = this.buffer.split('\n');
56
+ this.buffer = lines.pop() ?? '';
57
+ for (const line of lines) {
58
+ const trimmed = line.trim();
59
+ if (!trimmed) continue;
60
+ try {
61
+ const msg = JSON.parse(trimmed);
62
+ if (msg.id !== undefined && this.pending.has(msg.id)) {
63
+ const p = this.pending.get(msg.id)!;
64
+ this.pending.delete(msg.id);
65
+ if (msg.error) {
66
+ p.reject(new Error(msg.error.message || JSON.stringify(msg.error)));
67
+ } else {
68
+ p.resolve(msg.result);
69
+ }
70
+ }
71
+ } catch { /* skip non-JSON lines */ }
72
+ }
73
+ }
74
+
75
+ private sendRequest(method: string, params?: Record<string, unknown>): Promise<any> {
76
+ return new Promise((resolve, reject) => {
77
+ if (!this.process?.stdin?.writable) {
78
+ reject(new Error('MCP server not connected'));
79
+ return;
80
+ }
81
+ const id = this.nextId++;
82
+ this.pending.set(id, { resolve, reject });
83
+ const msg = JSON.stringify({ jsonrpc: '2.0', method, params: params ?? {}, id });
84
+ this.process.stdin.write(msg + '\n');
85
+
86
+ // Timeout after 30s
87
+ setTimeout(() => {
88
+ if (this.pending.has(id)) {
89
+ this.pending.delete(id);
90
+ reject(new Error(`MCP request timed out: ${method}`));
91
+ }
92
+ }, 30000);
93
+ });
94
+ }
95
+
96
+ private sendNotification(method: string, params: Record<string, unknown>): void {
97
+ if (!this.process?.stdin?.writable) return;
98
+ const msg = JSON.stringify({ jsonrpc: '2.0', method, params });
99
+ this.process.stdin.write(msg + '\n');
100
+ }
101
+
102
+ async listTools(): Promise<MCPToolDefinition[]> {
103
+ const result = await this.sendRequest('tools/list');
104
+ return (result.tools ?? []).map((t: any) => ({
105
+ name: t.name,
106
+ description: t.description ?? '',
107
+ inputSchema: t.inputSchema ?? {},
108
+ }));
109
+ }
110
+
111
+ async callTool(name: string, input: Record<string, unknown>): Promise<MCPToolResult> {
112
+ const result = await this.sendRequest('tools/call', { name, arguments: input });
113
+ const content = (result.content ?? [])
114
+ .map((c: any) => c.text ?? JSON.stringify(c))
115
+ .join('\n');
116
+ return { content, isError: result.isError ?? false };
117
+ }
118
+
119
+ async disconnect(): Promise<void> {
120
+ if (this.process) {
121
+ this.process.kill();
122
+ this.process = null;
123
+ }
124
+ this.connected = false;
125
+ this.pending.clear();
126
+ }
127
+
128
+ isConnected(): boolean {
129
+ return this.connected;
130
+ }
131
+ }
@@ -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
+ });
@@ -0,0 +1,246 @@
1
+ // AG-UI Protocol Tests
2
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
3
+ import {
4
+ AGUIEventEmitter,
5
+ AGUIServer,
6
+ AGUIClient,
7
+ AGUI_EVENT_TYPES,
8
+ isValidEventType,
9
+ } from '../src/protocols/agui';
10
+ import type { AGUIEvent, AGUIRunRequest } from '../src/protocols/agui';
11
+
12
+ // ─── Mock ServerResponse ─────────────────────────────────────
13
+
14
+ function createMockRes() {
15
+ const chunks: string[] = [];
16
+ return {
17
+ chunks,
18
+ writeHead: vi.fn(),
19
+ write: vi.fn((data: string) => { chunks.push(data); return true; }),
20
+ end: vi.fn(),
21
+ };
22
+ }
23
+
24
+ function parseSSEChunks(chunks: string[]): AGUIEvent[] {
25
+ return chunks
26
+ .filter(c => c.startsWith('data: '))
27
+ .map(c => JSON.parse(c.slice(6).trim()));
28
+ }
29
+
30
+ // ─── Tests ───────────────────────────────────────────────────
31
+
32
+ describe('AG-UI Protocol', () => {
33
+ describe('isValidEventType', () => {
34
+ it('should validate known event types', () => {
35
+ expect(isValidEventType('TEXT_MESSAGE_START')).toBe(true);
36
+ expect(isValidEventType('RUN_FINISHED')).toBe(true);
37
+ expect(isValidEventType('CUSTOM')).toBe(true);
38
+ });
39
+
40
+ it('should reject unknown event types', () => {
41
+ expect(isValidEventType('UNKNOWN')).toBe(false);
42
+ expect(isValidEventType('')).toBe(false);
43
+ });
44
+
45
+ it('should have all 15 event types', () => {
46
+ expect(AGUI_EVENT_TYPES.length).toBe(15);
47
+ });
48
+ });
49
+
50
+ describe('AGUIEventEmitter', () => {
51
+ let res: ReturnType<typeof createMockRes>;
52
+ let emitter: AGUIEventEmitter;
53
+
54
+ beforeEach(() => {
55
+ res = createMockRes();
56
+ emitter = new AGUIEventEmitter(res as any);
57
+ });
58
+
59
+ it('should emit SSE-formatted events', () => {
60
+ emitter.emit({ type: 'RUN_STARTED', runId: 'r1', timestamp: '2025-01-01T00:00:00Z' });
61
+ expect(res.chunks.length).toBe(1);
62
+ expect(res.chunks[0]).toMatch(/^data: \{.*\}\n\n$/);
63
+ const parsed = JSON.parse(res.chunks[0].slice(6));
64
+ expect(parsed.type).toBe('RUN_STARTED');
65
+ expect(parsed.runId).toBe('r1');
66
+ });
67
+
68
+ it('should emit textStart/textContent/textEnd flow', () => {
69
+ emitter.textStart('msg1');
70
+ emitter.textContent('msg1', 'Hello');
71
+ emitter.textContent('msg1', ' world');
72
+ emitter.textEnd('msg1');
73
+ const events = parseSSEChunks(res.chunks);
74
+ expect(events.length).toBe(4);
75
+ expect(events[0].type).toBe('TEXT_MESSAGE_START');
76
+ expect(events[0].messageId).toBe('msg1');
77
+ expect((events[0] as any).role).toBe('assistant');
78
+ expect(events[1].type).toBe('TEXT_MESSAGE_CONTENT');
79
+ expect((events[1] as any).delta).toBe('Hello');
80
+ expect(events[2].type).toBe('TEXT_MESSAGE_CONTENT');
81
+ expect((events[2] as any).delta).toBe(' world');
82
+ expect(events[3].type).toBe('TEXT_MESSAGE_END');
83
+ });
84
+
85
+ it('should emit tool call flow', () => {
86
+ emitter.toolCallStart('tc1', 'search');
87
+ emitter.toolCallArgs('tc1', '{"q":"test"}');
88
+ emitter.toolCallEnd('tc1');
89
+ const events = parseSSEChunks(res.chunks);
90
+ expect(events.length).toBe(3);
91
+ expect(events[0].type).toBe('TOOL_CALL_START');
92
+ expect((events[0] as any).toolCallName).toBe('search');
93
+ expect(events[1].type).toBe('TOOL_CALL_ARGS');
94
+ expect(events[2].type).toBe('TOOL_CALL_END');
95
+ });
96
+
97
+ it('should emit runStarted/runFinished', () => {
98
+ emitter.runStarted('r1', 'thread1');
99
+ emitter.runFinished('r1');
100
+ const events = parseSSEChunks(res.chunks);
101
+ expect(events[0].type).toBe('RUN_STARTED');
102
+ expect((events[0] as any).threadId).toBe('thread1');
103
+ expect(events[1].type).toBe('RUN_FINISHED');
104
+ });
105
+
106
+ it('should emit runError', () => {
107
+ emitter.runError('r1', 'Something went wrong', 'INTERNAL');
108
+ const events = parseSSEChunks(res.chunks);
109
+ expect(events[0].type).toBe('RUN_ERROR');
110
+ expect((events[0] as any).message).toBe('Something went wrong');
111
+ expect((events[0] as any).code).toBe('INTERNAL');
112
+ });
113
+
114
+ it('should emit stateSnapshot', () => {
115
+ emitter.stateSnapshot({ count: 42 });
116
+ const events = parseSSEChunks(res.chunks);
117
+ expect(events[0].type).toBe('STATE_SNAPSHOT');
118
+ expect((events[0] as any).snapshot.count).toBe(42);
119
+ });
120
+
121
+ it('should emit stateDelta', () => {
122
+ emitter.stateDelta([{ op: 'replace', path: '/count', value: 43 }]);
123
+ const events = parseSSEChunks(res.chunks);
124
+ expect(events[0].type).toBe('STATE_DELTA');
125
+ expect((events[0] as any).delta[0].op).toBe('replace');
126
+ });
127
+
128
+ it('should not emit after close', () => {
129
+ emitter.close();
130
+ emitter.textStart('msg1');
131
+ expect(res.chunks.length).toBe(0);
132
+ expect(res.end).toHaveBeenCalled();
133
+ });
134
+
135
+ it('should include timestamp on convenience methods', () => {
136
+ emitter.textStart('msg1');
137
+ const events = parseSSEChunks(res.chunks);
138
+ expect(events[0].timestamp).toBeDefined();
139
+ expect(typeof events[0].timestamp).toBe('string');
140
+ });
141
+
142
+ it('should emit step events', () => {
143
+ emitter.stepStarted('s1', 'process');
144
+ emitter.stepFinished('s1');
145
+ const events = parseSSEChunks(res.chunks);
146
+ expect(events[0].type).toBe('STEP_STARTED');
147
+ expect((events[0] as any).stepName).toBe('process');
148
+ expect(events[1].type).toBe('STEP_FINISHED');
149
+ });
150
+
151
+ it('should emit custom events', () => {
152
+ emitter.custom('my_event', { foo: 'bar' });
153
+ const events = parseSSEChunks(res.chunks);
154
+ expect(events[0].type).toBe('CUSTOM');
155
+ expect((events[0] as any).name).toBe('my_event');
156
+ expect((events[0] as any).value.foo).toBe('bar');
157
+ });
158
+
159
+ it('should emit messagesSnapshot', () => {
160
+ emitter.messagesSnapshot([{ id: 'm1', role: 'user', content: 'hi' }]);
161
+ const events = parseSSEChunks(res.chunks);
162
+ expect(events[0].type).toBe('MESSAGES_SNAPSHOT');
163
+ expect((events[0] as any).messages[0].content).toBe('hi');
164
+ });
165
+ });
166
+
167
+ describe('AGUIServer', () => {
168
+ it('should construct with default path', () => {
169
+ const mockAgent = { handleMessage: vi.fn(), handleMessageStream: vi.fn() };
170
+ const server = new AGUIServer(mockAgent as any);
171
+ expect(server).toBeDefined();
172
+ });
173
+
174
+ it('should handle run request with mock agent', async () => {
175
+ const mockAgent = {
176
+ handleMessage: vi.fn().mockResolvedValue({ content: 'Hello!' }),
177
+ handleMessageStream: async function* () { yield 'Hel'; yield 'lo!'; },
178
+ };
179
+ const server = new AGUIServer(mockAgent as any);
180
+ const res = createMockRes();
181
+
182
+ // Simulate request
183
+ const body = JSON.stringify({
184
+ messages: [{ id: 'msg1', role: 'user', content: 'Hi' }],
185
+ });
186
+ const req = {
187
+ [Symbol.asyncIterator]: async function* () { yield body; },
188
+ };
189
+
190
+ await server.handleRun(req as any, res as any);
191
+
192
+ expect(res.writeHead).toHaveBeenCalledWith(200, expect.objectContaining({
193
+ 'Content-Type': 'text/event-stream',
194
+ }));
195
+
196
+ const events = parseSSEChunks(res.chunks);
197
+ const types = events.map(e => e.type);
198
+ expect(types).toContain('RUN_STARTED');
199
+ expect(types).toContain('TEXT_MESSAGE_START');
200
+ expect(types).toContain('TEXT_MESSAGE_CONTENT');
201
+ expect(types).toContain('TEXT_MESSAGE_END');
202
+ expect(types).toContain('RUN_FINISHED');
203
+ });
204
+
205
+ it('should return 400 for invalid JSON', async () => {
206
+ const mockAgent = { handleMessage: vi.fn() };
207
+ const server = new AGUIServer(mockAgent as any);
208
+ const res = createMockRes();
209
+ const req = { [Symbol.asyncIterator]: async function* () { yield 'not json'; } };
210
+
211
+ await server.handleRun(req as any, res as any);
212
+ expect(res.writeHead).toHaveBeenCalledWith(400, expect.any(Object));
213
+ });
214
+
215
+ it('should return 400 for missing messages', async () => {
216
+ const mockAgent = { handleMessage: vi.fn() };
217
+ const server = new AGUIServer(mockAgent as any);
218
+ const res = createMockRes();
219
+ const req = { [Symbol.asyncIterator]: async function* () { yield '{}'; } };
220
+
221
+ await server.handleRun(req as any, res as any);
222
+ expect(res.writeHead).toHaveBeenCalledWith(400, expect.any(Object));
223
+ });
224
+ });
225
+
226
+ describe('AGUIClient', () => {
227
+ it('should construct with endpoint', () => {
228
+ const client = new AGUIClient('http://localhost:3000/agui');
229
+ expect(client).toBeDefined();
230
+ });
231
+
232
+ it('should abort cleanly', () => {
233
+ const client = new AGUIClient('http://localhost:3000/agui');
234
+ // Should not throw when no active request
235
+ client.abort();
236
+ });
237
+ });
238
+
239
+ describe('Protocol list includes agui', () => {
240
+ it('should have agui in AGUI_EVENT_TYPES constants', () => {
241
+ expect(AGUI_EVENT_TYPES).toContain('TEXT_MESSAGE_START');
242
+ expect(AGUI_EVENT_TYPES).toContain('RUN_STARTED');
243
+ expect(AGUI_EVENT_TYPES).toContain('TOOL_CALL_START');
244
+ });
245
+ });
246
+ });