opc-agent 2.0.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 (156) hide show
  1. package/dist/channels/email.d.ts +32 -26
  2. package/dist/channels/email.js +239 -62
  3. package/dist/channels/feishu.d.ts +21 -6
  4. package/dist/channels/feishu.js +225 -126
  5. package/dist/channels/websocket.d.ts +46 -3
  6. package/dist/channels/websocket.js +306 -37
  7. package/dist/channels/wechat.d.ts +33 -13
  8. package/dist/channels/wechat.js +229 -42
  9. package/dist/cli.js +712 -11
  10. package/dist/core/a2a.d.ts +17 -0
  11. package/dist/core/a2a.js +43 -1
  12. package/dist/core/agent.d.ts +16 -0
  13. package/dist/core/agent.js +108 -0
  14. package/dist/core/runtime.d.ts +6 -0
  15. package/dist/core/runtime.js +161 -2
  16. package/dist/core/sandbox.d.ts +26 -0
  17. package/dist/core/sandbox.js +117 -0
  18. package/dist/core/workflow-graph.d.ts +93 -0
  19. package/dist/core/workflow-graph.js +247 -0
  20. package/dist/doctor.d.ts +15 -0
  21. package/dist/doctor.js +183 -0
  22. package/dist/eval/index.d.ts +65 -0
  23. package/dist/eval/index.js +191 -0
  24. package/dist/index.d.ts +30 -6
  25. package/dist/index.js +60 -4
  26. package/dist/plugins/content-filter.d.ts +7 -0
  27. package/dist/plugins/content-filter.js +25 -0
  28. package/dist/plugins/index.d.ts +42 -0
  29. package/dist/plugins/index.js +108 -2
  30. package/dist/plugins/logger.d.ts +6 -0
  31. package/dist/plugins/logger.js +20 -0
  32. package/dist/plugins/rate-limiter.d.ts +7 -0
  33. package/dist/plugins/rate-limiter.js +35 -0
  34. package/dist/protocols/a2a/client.d.ts +25 -0
  35. package/dist/protocols/a2a/client.js +115 -0
  36. package/dist/protocols/a2a/index.d.ts +6 -0
  37. package/dist/protocols/a2a/index.js +12 -0
  38. package/dist/protocols/a2a/server.d.ts +41 -0
  39. package/dist/protocols/a2a/server.js +295 -0
  40. package/dist/protocols/a2a/types.d.ts +91 -0
  41. package/dist/protocols/a2a/types.js +15 -0
  42. package/dist/protocols/a2a/utils.d.ts +6 -0
  43. package/dist/protocols/a2a/utils.js +47 -0
  44. package/dist/protocols/agui/client.d.ts +10 -0
  45. package/dist/protocols/agui/client.js +75 -0
  46. package/dist/protocols/agui/index.d.ts +4 -0
  47. package/dist/protocols/agui/index.js +25 -0
  48. package/dist/protocols/agui/server.d.ts +37 -0
  49. package/dist/protocols/agui/server.js +191 -0
  50. package/dist/protocols/agui/types.d.ts +107 -0
  51. package/dist/protocols/agui/types.js +17 -0
  52. package/dist/protocols/index.d.ts +2 -0
  53. package/dist/protocols/index.js +19 -0
  54. package/dist/protocols/mcp/agent-tools.d.ts +11 -0
  55. package/dist/protocols/mcp/agent-tools.js +129 -0
  56. package/dist/protocols/mcp/index.d.ts +5 -0
  57. package/dist/protocols/mcp/index.js +11 -0
  58. package/dist/protocols/mcp/server.d.ts +31 -0
  59. package/dist/protocols/mcp/server.js +248 -0
  60. package/dist/protocols/mcp/types.d.ts +92 -0
  61. package/dist/protocols/mcp/types.js +17 -0
  62. package/dist/publish/index.d.ts +45 -0
  63. package/dist/publish/index.js +350 -0
  64. package/dist/schema/oad.d.ts +682 -65
  65. package/dist/schema/oad.js +36 -3
  66. package/dist/security/approval.d.ts +36 -0
  67. package/dist/security/approval.js +113 -0
  68. package/dist/security/index.d.ts +4 -0
  69. package/dist/security/index.js +8 -0
  70. package/dist/security/keys.d.ts +16 -0
  71. package/dist/security/keys.js +117 -0
  72. package/dist/studio/server.d.ts +63 -0
  73. package/dist/studio/server.js +625 -0
  74. package/dist/studio-ui/index.html +662 -0
  75. package/dist/telemetry/index.d.ts +93 -0
  76. package/dist/telemetry/index.js +285 -0
  77. package/package.json +5 -3
  78. package/scripts/install.ps1 +31 -0
  79. package/scripts/install.sh +40 -0
  80. package/src/channels/email.ts +351 -177
  81. package/src/channels/feishu.ts +349 -236
  82. package/src/channels/websocket.ts +399 -87
  83. package/src/channels/wechat.ts +329 -149
  84. package/src/cli.ts +783 -12
  85. package/src/core/a2a.ts +60 -0
  86. package/src/core/agent.ts +125 -0
  87. package/src/core/runtime.ts +127 -0
  88. package/src/core/sandbox.ts +143 -0
  89. package/src/core/workflow-graph.ts +365 -0
  90. package/src/doctor.ts +156 -0
  91. package/src/eval/index.ts +211 -0
  92. package/src/eval/suites/basic.json +16 -0
  93. package/src/eval/suites/memory.json +12 -0
  94. package/src/eval/suites/safety.json +14 -0
  95. package/src/index.ts +54 -6
  96. package/src/plugins/content-filter.ts +23 -0
  97. package/src/plugins/index.ts +133 -2
  98. package/src/plugins/logger.ts +18 -0
  99. package/src/plugins/rate-limiter.ts +38 -0
  100. package/src/protocols/a2a/client.ts +132 -0
  101. package/src/protocols/a2a/index.ts +8 -0
  102. package/src/protocols/a2a/server.ts +333 -0
  103. package/src/protocols/a2a/types.ts +88 -0
  104. package/src/protocols/a2a/utils.ts +50 -0
  105. package/src/protocols/agui/client.ts +83 -0
  106. package/src/protocols/agui/index.ts +4 -0
  107. package/src/protocols/agui/server.ts +218 -0
  108. package/src/protocols/agui/types.ts +153 -0
  109. package/src/protocols/index.ts +2 -0
  110. package/src/protocols/mcp/agent-tools.ts +134 -0
  111. package/src/protocols/mcp/index.ts +8 -0
  112. package/src/protocols/mcp/server.ts +262 -0
  113. package/src/protocols/mcp/types.ts +69 -0
  114. package/src/publish/index.ts +376 -0
  115. package/src/schema/oad.ts +39 -2
  116. package/src/security/approval.ts +131 -0
  117. package/src/security/index.ts +3 -0
  118. package/src/security/keys.ts +87 -0
  119. package/src/studio/server.ts +629 -0
  120. package/src/studio-ui/index.html +662 -0
  121. package/src/telemetry/index.ts +324 -0
  122. package/src/types/agent-workstation.d.ts +2 -0
  123. package/tests/a2a-protocol.test.ts +285 -0
  124. package/tests/agui-protocol.test.ts +246 -0
  125. package/tests/channels/discord.test.ts +79 -0
  126. package/tests/channels/email.test.ts +148 -0
  127. package/tests/channels/feishu.test.ts +123 -0
  128. package/tests/channels/telegram.test.ts +129 -0
  129. package/tests/channels/websocket.test.ts +53 -0
  130. package/tests/channels/wechat.test.ts +170 -0
  131. package/tests/chat-cli.test.ts +160 -0
  132. package/tests/daemon.test.ts +135 -0
  133. package/tests/deepbrain-wire.test.ts +234 -0
  134. package/tests/doctor.test.ts +38 -0
  135. package/tests/eval.test.ts +173 -0
  136. package/tests/init-role.test.ts +124 -0
  137. package/tests/mcp-client.test.ts +92 -0
  138. package/tests/mcp-server.test.ts +178 -0
  139. package/tests/plugin-a2a-enhanced.test.ts +230 -0
  140. package/tests/publish.test.ts +231 -0
  141. package/tests/scheduler.test.ts +200 -0
  142. package/tests/security-enhanced.test.ts +233 -0
  143. package/tests/skill-learner.test.ts +161 -0
  144. package/tests/studio.test.ts +229 -0
  145. package/tests/subagent.test.ts +63 -0
  146. package/tests/telemetry.test.ts +186 -0
  147. package/tests/tools/builtin-extended.test.ts +138 -0
  148. package/tests/workflow-graph.test.ts +279 -0
  149. package/tutorial/customer-service-agent/README.md +612 -0
  150. package/tutorial/customer-service-agent/SOUL.md +26 -0
  151. package/tutorial/customer-service-agent/agent.yaml +63 -0
  152. package/tutorial/customer-service-agent/package.json +19 -0
  153. package/tutorial/customer-service-agent/src/index.ts +69 -0
  154. package/tutorial/customer-service-agent/src/skills/faq.ts +27 -0
  155. package/tutorial/customer-service-agent/src/skills/ticket.ts +22 -0
  156. package/tutorial/customer-service-agent/tsconfig.json +14 -0
@@ -0,0 +1,262 @@
1
+ import { createServer, type IncomingMessage, type ServerResponse } from 'http';
2
+ import { createInterface } from 'readline';
3
+ import type {
4
+ MCPServerConfig, MCPServerToolDefinition, MCPResourceDefinition,
5
+ MCPPromptDefinition, JsonRpcRequest, JsonRpcResponse,
6
+ } from './types';
7
+ import { MCP_ERRORS } from './types';
8
+
9
+ export class MCPServer {
10
+ private config: MCPServerConfig;
11
+ private tools: Map<string, MCPServerToolDefinition> = new Map();
12
+ private resources: Map<string, MCPResourceDefinition> = new Map();
13
+ private prompts: Map<string, MCPPromptDefinition> = new Map();
14
+ private sseClients: Set<ServerResponse> = new Set();
15
+ private httpServer: ReturnType<typeof createServer> | null = null;
16
+
17
+ constructor(config: MCPServerConfig) {
18
+ this.config = config;
19
+ for (const t of config.tools ?? []) this.addTool(t);
20
+ for (const r of config.resources ?? []) this.addResource(r);
21
+ for (const p of config.prompts ?? []) this.addPrompt(p);
22
+ }
23
+
24
+ addTool(tool: MCPServerToolDefinition): void {
25
+ this.tools.set(tool.name, tool);
26
+ }
27
+
28
+ removeTool(name: string): void {
29
+ this.tools.delete(name);
30
+ }
31
+
32
+ addResource(resource: MCPResourceDefinition): void {
33
+ this.resources.set(resource.uri, resource);
34
+ }
35
+
36
+ removeResource(uri: string): void {
37
+ this.resources.delete(uri);
38
+ }
39
+
40
+ addPrompt(prompt: MCPPromptDefinition): void {
41
+ this.prompts.set(prompt.name, prompt);
42
+ }
43
+
44
+ getToolCount(): number { return this.tools.size; }
45
+ getResourceCount(): number { return this.resources.size; }
46
+ getPromptCount(): number { return this.prompts.size; }
47
+ getConnectedClients(): number { return this.sseClients.size; }
48
+
49
+ /** Serve over stdio — one JSON-RPC message per line */
50
+ async serveStdio(): Promise<void> {
51
+ const rl = createInterface({ input: process.stdin, terminal: false });
52
+ rl.on('line', async (line) => {
53
+ const trimmed = line.trim();
54
+ if (!trimmed) return;
55
+ try {
56
+ const msg = JSON.parse(trimmed) as JsonRpcRequest;
57
+ const response = await this.handleMessage(msg);
58
+ if (response) {
59
+ process.stdout.write(JSON.stringify(response) + '\n');
60
+ }
61
+ } catch {
62
+ const err: JsonRpcResponse = {
63
+ jsonrpc: '2.0', id: null,
64
+ error: MCP_ERRORS.PARSE_ERROR,
65
+ };
66
+ process.stdout.write(JSON.stringify(err) + '\n');
67
+ }
68
+ });
69
+ }
70
+
71
+ /** Serve over HTTP + SSE */
72
+ async serveHTTP(port: number): Promise<void> {
73
+ this.httpServer = createServer((req, res) => this.handleHTTP(req, res));
74
+ return new Promise((resolve) => {
75
+ this.httpServer!.listen(port, () => resolve());
76
+ });
77
+ }
78
+
79
+ /** Mount on existing HTTP server at a path prefix */
80
+ mount(server: any, path = '/mcp'): void {
81
+ const orig = server.listeners('request')[0] as any;
82
+ server.removeAllListeners('request');
83
+ server.on('request', (req: IncomingMessage, res: ServerResponse) => {
84
+ if (req.url?.startsWith(path)) {
85
+ // Rewrite URL to strip prefix
86
+ req.url = req.url.slice(path.length) || '/';
87
+ this.handleHTTP(req, res);
88
+ } else if (orig) {
89
+ orig(req, res);
90
+ }
91
+ });
92
+ }
93
+
94
+ stop(): void {
95
+ this.httpServer?.close();
96
+ for (const client of this.sseClients) {
97
+ client.end();
98
+ }
99
+ this.sseClients.clear();
100
+ }
101
+
102
+ private handleHTTP(req: IncomingMessage, res: ServerResponse): void {
103
+ res.setHeader('Access-Control-Allow-Origin', '*');
104
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
105
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
106
+
107
+ if (req.method === 'OPTIONS') {
108
+ res.writeHead(204);
109
+ res.end();
110
+ return;
111
+ }
112
+
113
+ const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
114
+
115
+ if (url.pathname === '/sse' && req.method === 'GET') {
116
+ // SSE endpoint
117
+ res.writeHead(200, {
118
+ 'Content-Type': 'text/event-stream',
119
+ 'Cache-Control': 'no-cache',
120
+ 'Connection': 'keep-alive',
121
+ });
122
+ this.sseClients.add(res);
123
+ // Send endpoint info
124
+ res.write(`data: ${JSON.stringify({ type: 'endpoint', url: '/message' })}\n\n`);
125
+ req.on('close', () => this.sseClients.delete(res));
126
+ return;
127
+ }
128
+
129
+ if (url.pathname === '/message' && req.method === 'POST') {
130
+ let body = '';
131
+ req.on('data', (chunk) => { body += chunk; });
132
+ req.on('end', async () => {
133
+ try {
134
+ const msg = JSON.parse(body) as JsonRpcRequest;
135
+ const response = await this.handleMessage(msg);
136
+ if (response) {
137
+ // Send via SSE to all clients
138
+ for (const client of this.sseClients) {
139
+ client.write(`data: ${JSON.stringify(response)}\n\n`);
140
+ }
141
+ res.writeHead(200, { 'Content-Type': 'application/json' });
142
+ res.end(JSON.stringify(response));
143
+ } else {
144
+ res.writeHead(202);
145
+ res.end();
146
+ }
147
+ } catch {
148
+ res.writeHead(400, { 'Content-Type': 'application/json' });
149
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: MCP_ERRORS.PARSE_ERROR }));
150
+ }
151
+ });
152
+ return;
153
+ }
154
+
155
+ res.writeHead(404);
156
+ res.end('Not Found');
157
+ }
158
+
159
+ async handleMessage(msg: JsonRpcRequest): Promise<JsonRpcResponse | null> {
160
+ // Notifications (no id) don't get responses
161
+ if (msg.id === undefined) return null;
162
+
163
+ const id = msg.id;
164
+ try {
165
+ switch (msg.method) {
166
+ case 'initialize':
167
+ return this.rpcResult(id, {
168
+ protocolVersion: '2024-11-05',
169
+ capabilities: {
170
+ tools: this.tools.size > 0 ? { listChanged: true } : undefined,
171
+ resources: this.resources.size > 0 ? { subscribe: false, listChanged: true } : undefined,
172
+ prompts: this.prompts.size > 0 ? { listChanged: true } : undefined,
173
+ },
174
+ serverInfo: { name: this.config.name, version: this.config.version },
175
+ });
176
+
177
+ case 'tools/list':
178
+ return this.rpcResult(id, {
179
+ tools: Array.from(this.tools.values()).map(t => ({
180
+ name: t.name,
181
+ description: t.description,
182
+ inputSchema: t.inputSchema,
183
+ })),
184
+ });
185
+
186
+ case 'tools/call': {
187
+ const { name, arguments: args } = msg.params ?? {};
188
+ const tool = this.tools.get(name);
189
+ if (!tool) return this.rpcError(id, MCP_ERRORS.TOOL_NOT_FOUND);
190
+ // Validate required fields
191
+ const schema = tool.inputSchema;
192
+ if (schema?.required && Array.isArray(schema.required)) {
193
+ for (const field of schema.required) {
194
+ if (args?.[field] === undefined) {
195
+ return this.rpcError(id, { code: -32602, message: `Missing required parameter: ${field}` });
196
+ }
197
+ }
198
+ }
199
+ try {
200
+ const result = await tool.handler(args ?? {});
201
+ return this.rpcResult(id, {
202
+ content: [{ type: 'text', text: typeof result === 'string' ? result : JSON.stringify(result) }],
203
+ });
204
+ } catch (err: any) {
205
+ return this.rpcResult(id, {
206
+ content: [{ type: 'text', text: err.message || 'Tool execution failed' }],
207
+ isError: true,
208
+ });
209
+ }
210
+ }
211
+
212
+ case 'resources/list':
213
+ return this.rpcResult(id, {
214
+ resources: Array.from(this.resources.values()).map(r => ({
215
+ uri: r.uri, name: r.name, description: r.description, mimeType: r.mimeType,
216
+ })),
217
+ });
218
+
219
+ case 'resources/read': {
220
+ const { uri } = msg.params ?? {};
221
+ const resource = this.resources.get(uri);
222
+ if (!resource) return this.rpcError(id, MCP_ERRORS.RESOURCE_NOT_FOUND);
223
+ const content = await resource.handler();
224
+ return this.rpcResult(id, {
225
+ contents: [{ uri, mimeType: resource.mimeType || 'text/plain', text: content }],
226
+ });
227
+ }
228
+
229
+ case 'prompts/list':
230
+ return this.rpcResult(id, {
231
+ prompts: Array.from(this.prompts.values()).map(p => ({
232
+ name: p.name, description: p.description,
233
+ arguments: p.arguments,
234
+ })),
235
+ });
236
+
237
+ case 'prompts/get': {
238
+ const { name, arguments: promptArgs } = msg.params ?? {};
239
+ const prompt = this.prompts.get(name);
240
+ if (!prompt) return this.rpcError(id, MCP_ERRORS.PROMPT_NOT_FOUND);
241
+ const messages = prompt.handler
242
+ ? await prompt.handler(promptArgs ?? {})
243
+ : [{ role: 'user' as const, content: { type: 'text' as const, text: prompt.description || '' } }];
244
+ return this.rpcResult(id, { description: prompt.description, messages });
245
+ }
246
+
247
+ default:
248
+ return this.rpcError(id, MCP_ERRORS.METHOD_NOT_FOUND);
249
+ }
250
+ } catch (err: any) {
251
+ return this.rpcError(id, { ...MCP_ERRORS.INTERNAL_ERROR, data: err.message });
252
+ }
253
+ }
254
+
255
+ private rpcResult(id: number | string, result: any): JsonRpcResponse {
256
+ return { jsonrpc: '2.0', id, result };
257
+ }
258
+
259
+ private rpcError(id: number | string, error: { code: number; message: string; data?: any }): JsonRpcResponse {
260
+ return { jsonrpc: '2.0', id, error };
261
+ }
262
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * MCP Server types — JSON-RPC 2.0 based Model Context Protocol
3
+ */
4
+
5
+ export interface MCPServerConfig {
6
+ name: string;
7
+ version: string;
8
+ tools?: MCPServerToolDefinition[];
9
+ resources?: MCPResourceDefinition[];
10
+ prompts?: MCPPromptDefinition[];
11
+ }
12
+
13
+ export interface MCPServerToolDefinition {
14
+ name: string;
15
+ description: string;
16
+ inputSchema: Record<string, any>;
17
+ handler: (args: any) => Promise<any>;
18
+ }
19
+
20
+ export interface MCPResourceDefinition {
21
+ uri: string;
22
+ name: string;
23
+ description?: string;
24
+ mimeType?: string;
25
+ handler: () => Promise<string>;
26
+ }
27
+
28
+ export interface MCPPromptDefinition {
29
+ name: string;
30
+ description?: string;
31
+ arguments?: MCPPromptArgument[];
32
+ handler?: (args: Record<string, string>) => Promise<MCPPromptMessage[]>;
33
+ }
34
+
35
+ export interface MCPPromptArgument {
36
+ name: string;
37
+ description?: string;
38
+ required?: boolean;
39
+ }
40
+
41
+ export interface MCPPromptMessage {
42
+ role: 'user' | 'assistant';
43
+ content: { type: 'text'; text: string };
44
+ }
45
+
46
+ export interface JsonRpcRequest {
47
+ jsonrpc: '2.0';
48
+ id?: number | string;
49
+ method: string;
50
+ params?: any;
51
+ }
52
+
53
+ export interface JsonRpcResponse {
54
+ jsonrpc: '2.0';
55
+ id: number | string | null;
56
+ result?: any;
57
+ error?: { code: number; message: string; data?: any };
58
+ }
59
+
60
+ export const MCP_ERRORS = {
61
+ PARSE_ERROR: { code: -32700, message: 'Parse error' },
62
+ INVALID_REQUEST: { code: -32600, message: 'Invalid Request' },
63
+ METHOD_NOT_FOUND: { code: -32601, message: 'Method not found' },
64
+ INVALID_PARAMS: { code: -32602, message: 'Invalid params' },
65
+ INTERNAL_ERROR: { code: -32603, message: 'Internal error' },
66
+ TOOL_NOT_FOUND: { code: -32001, message: 'Tool not found' },
67
+ RESOURCE_NOT_FOUND: { code: -32002, message: 'Resource not found' },
68
+ PROMPT_NOT_FOUND: { code: -32003, message: 'Prompt not found' },
69
+ } as const;
@@ -0,0 +1,376 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import * as crypto from 'crypto';
4
+ import * as yaml from 'js-yaml';
5
+ import { execSync } from 'child_process';
6
+
7
+ // ─── Types ───────────────────────────────────────────────────
8
+
9
+ export interface PackageManifest {
10
+ name: string;
11
+ version: string;
12
+ description: string;
13
+ author: string;
14
+ license: string;
15
+ agent: {
16
+ model: string;
17
+ provider: string;
18
+ channels: string[];
19
+ skills: string[];
20
+ tools: string[];
21
+ };
22
+ files: string[];
23
+ checksum: string;
24
+ createdAt: string;
25
+ }
26
+
27
+ export interface PublishOptions {
28
+ dryRun?: boolean;
29
+ registry?: string;
30
+ tag?: string;
31
+ access?: 'public' | 'private';
32
+ }
33
+
34
+ // ─── Ignore patterns ────────────────────────────────────────
35
+
36
+ const DEFAULT_IGNORE = [
37
+ 'node_modules',
38
+ '.git',
39
+ '.env',
40
+ '.opc',
41
+ '*.log',
42
+ 'dist',
43
+ '.DS_Store',
44
+ 'Thumbs.db',
45
+ ];
46
+
47
+ function loadIgnorePatterns(dir: string): string[] {
48
+ const opcIgnore = path.join(dir, '.opcignore');
49
+ const gitIgnore = path.join(dir, '.gitignore');
50
+
51
+ let lines: string[] = [];
52
+ if (fs.existsSync(opcIgnore)) {
53
+ lines = fs.readFileSync(opcIgnore, 'utf-8').split('\n');
54
+ } else if (fs.existsSync(gitIgnore)) {
55
+ lines = fs.readFileSync(gitIgnore, 'utf-8').split('\n');
56
+ }
57
+
58
+ const patterns = lines
59
+ .map(l => l.trim())
60
+ .filter(l => l && !l.startsWith('#'));
61
+
62
+ // Merge with defaults (deduplicate)
63
+ const all = new Set([...DEFAULT_IGNORE, ...patterns]);
64
+ return Array.from(all);
65
+ }
66
+
67
+ function matchesPattern(filePath: string, pattern: string): boolean {
68
+ // Normalize separators
69
+ const normalized = filePath.replace(/\\/g, '/');
70
+ const p = pattern.replace(/\\/g, '/').replace(/\/$/, '');
71
+
72
+ // Exact directory/file match
73
+ if (normalized === p || normalized.startsWith(p + '/')) return true;
74
+
75
+ // Basename match (e.g. ".env" matches any ".env" at any depth)
76
+ const basename = path.basename(normalized);
77
+ if (basename === p) return true;
78
+
79
+ // Simple glob: *.ext
80
+ if (p.startsWith('*.')) {
81
+ const ext = p.slice(1); // e.g. ".log"
82
+ if (basename.endsWith(ext)) return true;
83
+ }
84
+
85
+ // Directory at any depth: "tests/" pattern
86
+ const segments = normalized.split('/');
87
+ if (segments.includes(p)) return true;
88
+
89
+ return false;
90
+ }
91
+
92
+ function isIgnored(filePath: string, patterns: string[]): boolean {
93
+ return patterns.some(p => matchesPattern(filePath, p));
94
+ }
95
+
96
+ // ─── File walker ────────────────────────────────────────────
97
+
98
+ function walkDir(dir: string, base: string, patterns: string[]): string[] {
99
+ const results: string[] = [];
100
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
101
+
102
+ for (const entry of entries) {
103
+ const rel = path.join(base, entry.name).replace(/\\/g, '/');
104
+ if (isIgnored(rel, patterns)) continue;
105
+
106
+ if (entry.isDirectory()) {
107
+ results.push(...walkDir(path.join(dir, entry.name), rel, patterns));
108
+ } else if (entry.isFile()) {
109
+ results.push(rel);
110
+ }
111
+ }
112
+ return results;
113
+ }
114
+
115
+ // ─── AgentPackager ──────────────────────────────────────────
116
+
117
+ export class AgentPackager {
118
+ async validate(dir: string): Promise<{ valid: boolean; errors: string[]; warnings: string[] }> {
119
+ const errors: string[] = [];
120
+ const warnings: string[] = [];
121
+
122
+ // Required files
123
+ if (!fs.existsSync(path.join(dir, 'agent.yaml'))) {
124
+ errors.push('Missing agent.yaml');
125
+ }
126
+ if (!fs.existsSync(path.join(dir, 'package.json'))) {
127
+ errors.push('Missing package.json');
128
+ }
129
+
130
+ // Recommended files
131
+ if (!fs.existsSync(path.join(dir, 'SOUL.md'))) {
132
+ warnings.push('Missing SOUL.md (recommended)');
133
+ }
134
+ if (!fs.existsSync(path.join(dir, 'README.md'))) {
135
+ warnings.push('Missing README.md');
136
+ }
137
+
138
+ // Validate agent.yaml content if it exists
139
+ if (fs.existsSync(path.join(dir, 'agent.yaml'))) {
140
+ try {
141
+ const raw = fs.readFileSync(path.join(dir, 'agent.yaml'), 'utf-8');
142
+ const config = yaml.load(raw) as any;
143
+
144
+ if (!config?.metadata?.name) {
145
+ errors.push('agent.yaml: missing metadata.name');
146
+ } else {
147
+ const name = config.metadata.name;
148
+ if (name !== name.toLowerCase()) {
149
+ errors.push('agent.yaml: metadata.name must be lowercase');
150
+ }
151
+ if (/\s/.test(name)) {
152
+ errors.push('agent.yaml: metadata.name must not contain spaces');
153
+ }
154
+ }
155
+
156
+ if (!config?.metadata?.version) {
157
+ errors.push('agent.yaml: missing metadata.version');
158
+ } else {
159
+ const ver = config.metadata.version;
160
+ if (!/^\d+\.\d+\.\d+/.test(ver)) {
161
+ errors.push(`agent.yaml: invalid version format "${ver}" (expected semver)`);
162
+ }
163
+ }
164
+ } catch (e) {
165
+ errors.push(`agent.yaml: invalid YAML — ${e instanceof Error ? e.message : e}`);
166
+ }
167
+ }
168
+
169
+ // Validate package.json
170
+ if (fs.existsSync(path.join(dir, 'package.json'))) {
171
+ try {
172
+ JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));
173
+ } catch {
174
+ errors.push('package.json: invalid JSON');
175
+ }
176
+ }
177
+
178
+ return { valid: errors.length === 0, errors, warnings };
179
+ }
180
+
181
+ async listFiles(dir: string): Promise<string[]> {
182
+ const patterns = loadIgnorePatterns(dir);
183
+ return walkDir(dir, '', patterns);
184
+ }
185
+
186
+ async pack(dir: string): Promise<{ path: string; manifest: PackageManifest }> {
187
+ // 1. Validate
188
+ const validation = await this.validate(dir);
189
+ if (!validation.valid) {
190
+ throw new Error(`Validation failed:\n ${validation.errors.join('\n ')}`);
191
+ }
192
+
193
+ // 2. Read configs
194
+ const agentYaml = yaml.load(fs.readFileSync(path.join(dir, 'agent.yaml'), 'utf-8')) as any;
195
+ const pkgJson = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));
196
+
197
+ const meta = agentYaml.metadata ?? {};
198
+ const spec = agentYaml.spec ?? {};
199
+
200
+ // 3. Collect files
201
+ const files = await this.listFiles(dir);
202
+
203
+ // 4. Create manifest
204
+ const manifest: PackageManifest = {
205
+ name: meta.name ?? pkgJson.name ?? 'unknown',
206
+ version: meta.version ?? pkgJson.version ?? '0.0.0',
207
+ description: meta.description ?? pkgJson.description ?? '',
208
+ author: meta.author ?? pkgJson.author ?? '',
209
+ license: meta.license ?? pkgJson.license ?? 'UNLICENSED',
210
+ agent: {
211
+ model: spec.model ?? '',
212
+ provider: spec.provider?.default ?? '',
213
+ channels: (spec.channels ?? []).map((c: any) => c.type ?? String(c)),
214
+ skills: (spec.skills ?? []).map((s: any) => s.name ?? String(s)),
215
+ tools: (spec.tools ?? []).map((t: any) => t.name ?? String(t)),
216
+ },
217
+ files,
218
+ checksum: '', // computed after tarball
219
+ createdAt: new Date().toISOString(),
220
+ };
221
+
222
+ // Write manifest into dir temporarily
223
+ const manifestPath = path.join(dir, 'manifest.json');
224
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
225
+
226
+ // 5. Create tarball
227
+ const tarName = `${manifest.name}-${manifest.version}.opc.tgz`;
228
+ const outputPath = path.resolve(dir, '..', tarName);
229
+
230
+ // Include manifest.json in file list
231
+ const allFiles = ['manifest.json', ...files];
232
+
233
+ try {
234
+ // Try using system tar
235
+ const fileListPath = path.join(dir, '.opc-filelist');
236
+ fs.writeFileSync(fileListPath, allFiles.join('\n'));
237
+
238
+ execSync(
239
+ `tar czf "${outputPath}" -C "${dir}" -T "${fileListPath}"`,
240
+ { stdio: 'pipe' },
241
+ );
242
+
243
+ // Cleanup temp files
244
+ try { fs.unlinkSync(fileListPath); } catch { /* ignore */ }
245
+ } catch {
246
+ // Fallback: use node zlib + simple tar via exec
247
+ // On Windows, try PowerShell Compress-Archive as .zip then rename
248
+ try {
249
+ const tempZip = outputPath.replace('.tgz', '.zip');
250
+ const absFiles = allFiles.map(f => `"${path.join(dir, f)}"`).join(',');
251
+ execSync(
252
+ `powershell -NoProfile -Command "Compress-Archive -Path ${absFiles} -DestinationPath '${tempZip}' -Force"`,
253
+ { stdio: 'pipe' },
254
+ );
255
+ // Rename .zip to .tgz (not ideal but functional)
256
+ if (fs.existsSync(tempZip)) {
257
+ fs.renameSync(tempZip, outputPath);
258
+ }
259
+ } catch (e2) {
260
+ // Last resort: create a simple tar-like archive manually
261
+ // Bundle all files as a JSON + base64 archive
262
+ const archive: Record<string, string> = {};
263
+ for (const f of allFiles) {
264
+ const content = fs.readFileSync(path.join(dir, f));
265
+ archive[f] = content.toString('base64');
266
+ }
267
+ const archiveJson = JSON.stringify(archive);
268
+ const { gzipSync } = require('zlib');
269
+ const compressed = gzipSync(Buffer.from(archiveJson));
270
+ fs.writeFileSync(outputPath, compressed);
271
+ }
272
+ }
273
+
274
+ // Cleanup manifest from source dir
275
+ try { fs.unlinkSync(manifestPath); } catch { /* ignore */ }
276
+
277
+ // 6. Calculate checksum
278
+ const fileBuffer = fs.readFileSync(outputPath);
279
+ manifest.checksum = crypto.createHash('sha256').update(fileBuffer).digest('hex');
280
+
281
+ return { path: outputPath, manifest };
282
+ }
283
+ }
284
+
285
+ // ─── AgentPublisher ─────────────────────────────────────────
286
+
287
+ export class AgentPublisher {
288
+ async publish(
289
+ packagePath: string,
290
+ manifest: PackageManifest,
291
+ options: PublishOptions = {},
292
+ ): Promise<{ success: boolean; url?: string }> {
293
+ const tag = options.tag ?? 'latest';
294
+ const access = options.access ?? 'public';
295
+ const registry = options.registry ?? 'https://registry.npmjs.org';
296
+
297
+ if (options.dryRun) {
298
+ console.log('\n📦 Dry run — would publish:\n');
299
+ console.log(` Name: ${manifest.name}`);
300
+ console.log(` Version: ${manifest.version}`);
301
+ console.log(` Tag: ${tag}`);
302
+ console.log(` Access: ${access}`);
303
+ console.log(` Registry: ${registry}`);
304
+ console.log(` Files: ${manifest.files.length}`);
305
+ console.log(` Checksum: ${manifest.checksum}`);
306
+ console.log(` Package: ${packagePath}`);
307
+ console.log();
308
+ return { success: true };
309
+ }
310
+
311
+ // For now: placeholder — future OPC registry integration
312
+ console.log(`\n📦 Publishing ${manifest.name}@${manifest.version} (tag: ${tag})...`);
313
+ console.log(` Registry: ${registry}`);
314
+ console.log(` Package: ${packagePath}`);
315
+ console.log(` Checksum: ${manifest.checksum}`);
316
+
317
+ // Future: actual npm publish or OPC registry API call
318
+ // execSync(`npm publish "${packagePath}" --tag ${tag} --access ${access}`, { stdio: 'inherit' });
319
+
320
+ console.log(`\n✅ Published ${manifest.name}@${manifest.version}`);
321
+ return {
322
+ success: true,
323
+ url: `${registry}/${manifest.name}`,
324
+ };
325
+ }
326
+ }
327
+
328
+ // ─── AgentInstaller ─────────────────────────────────────────
329
+
330
+ export class AgentInstaller {
331
+ async install(source: string, targetDir: string): Promise<void> {
332
+ if (!fs.existsSync(targetDir)) {
333
+ fs.mkdirSync(targetDir, { recursive: true });
334
+ }
335
+
336
+ if (source.endsWith('.opc.tgz')) {
337
+ // Extract tarball
338
+ if (!fs.existsSync(source)) {
339
+ throw new Error(`Package not found: ${source}`);
340
+ }
341
+
342
+ try {
343
+ // Try system tar
344
+ execSync(`tar xzf "${source}" -C "${targetDir}"`, { stdio: 'pipe' });
345
+ } catch {
346
+ // Fallback: try reading as gzipped JSON archive
347
+ const { gunzipSync } = require('zlib');
348
+ const compressed = fs.readFileSync(source);
349
+ try {
350
+ const decompressed = gunzipSync(compressed);
351
+ const archive = JSON.parse(decompressed.toString());
352
+ for (const [filePath, base64Content] of Object.entries(archive)) {
353
+ const fullPath = path.join(targetDir, filePath);
354
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
355
+ fs.writeFileSync(fullPath, Buffer.from(base64Content as string, 'base64'));
356
+ }
357
+ } catch {
358
+ throw new Error('Failed to extract package — unsupported archive format');
359
+ }
360
+ }
361
+
362
+ // Verify manifest
363
+ const manifestPath = path.join(targetDir, 'manifest.json');
364
+ if (fs.existsSync(manifestPath)) {
365
+ const manifest: PackageManifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
366
+ console.log(`✅ Installed ${manifest.name}@${manifest.version}`);
367
+ } else {
368
+ console.log('✅ Extracted package (no manifest found)');
369
+ }
370
+ } else {
371
+ // npm install
372
+ console.log(`📦 Installing from npm: ${source}`);
373
+ execSync(`npm install "${source}"`, { cwd: targetDir, stdio: 'inherit' });
374
+ }
375
+ }
376
+ }