@causyne/agent 1.20.38 → 1.20.39

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.
@@ -0,0 +1,631 @@
1
+ /**
2
+ * Code and Manifest Templates for PluginsFactory.
3
+ *
4
+ * Scaffolds production-grade, secure implementations for:
5
+ * 1. Native HTTP Plugin (Leanest, zero daemon overhead)
6
+ * 2. Native CLI Plugin (Subprocess wrapper)
7
+ * 3. Python Bridge Plugin (Lightweight JSON stdio bridge for Python libraries)
8
+ * 4. Stdio MCP Server (Zero-dependency JSON-RPC 2.0 stdio daemon)
9
+ */
10
+
11
+ import type { ServiceDescriptor, ServiceToolDescriptor } from './types.js';
12
+
13
+ export interface ScaffoldingPayload {
14
+ files: Array<{ relativePath: string; content: string }>;
15
+ entryPoint: string;
16
+ }
17
+
18
+ function sanitizeIdentifier(name: string): string {
19
+ return name.replace(/[^a-zA-Z0-9_]/g, '_');
20
+ }
21
+
22
+ /**
23
+ * Generates scaffold files for a Native HTTP Plugin.
24
+ */
25
+ export function generateHttpPluginScaffold(service: ServiceDescriptor): ScaffoldingPayload {
26
+ const capabilities = Array.from(new Set(['network', ...(service.capabilities || [])]));
27
+ const primaryTool = service.tools[0] || {
28
+ name: 'query',
29
+ description: `Execute request against ${service.name}`,
30
+ parameters: { type: 'object', properties: {} }
31
+ };
32
+
33
+ const manifest = {
34
+ schemaVersion: 1,
35
+ name: service.name,
36
+ version: '1.0.0',
37
+ description: service.description || `Native HTTP plugin for ${service.name}`,
38
+ capabilities,
39
+ tools: service.tools.map(tool => ({
40
+ name: tool.name,
41
+ description: tool.description,
42
+ parameters: tool.parameters,
43
+ entry: 'index.js',
44
+ export: tool.name === primaryTool.name ? 'execute' : tool.name,
45
+ timeoutMs: 30000
46
+ }))
47
+ };
48
+
49
+ const toolExecutors = service.tools.map(tool => {
50
+ const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
51
+ const httpMethod = tool.httpMethod || 'POST';
52
+ const httpPath = tool.httpPath || '/';
53
+ return `
54
+ /**
55
+ * ${tool.description}
56
+ */
57
+ export async function ${fnName}(args = {}, context = {}) {
58
+ const endpoint = ${JSON.stringify(service.endpoint || 'https://api.example.com')};
59
+ const url = new URL(${JSON.stringify(httpPath)}, endpoint).toString();
60
+ const authHeader = ${
61
+ service.authEnvVar
62
+ ? `process.env[${JSON.stringify(service.authEnvVar)}] ? \`Bearer \${process.env[${JSON.stringify(service.authEnvVar)}]}\` : undefined`
63
+ : 'undefined'
64
+ };
65
+
66
+ const headers = {
67
+ 'Accept': 'application/json',
68
+ 'Content-Type': 'application/json'
69
+ };
70
+ if (authHeader) headers['Authorization'] = authHeader;
71
+
72
+ try {
73
+ const response = await fetch(url, {
74
+ method: ${JSON.stringify(httpMethod)},
75
+ headers,
76
+ body: ${httpMethod !== 'GET' ? 'JSON.stringify(args)' : 'undefined'}
77
+ });
78
+
79
+ if (!response.ok) {
80
+ const errorText = await response.text();
81
+ return {
82
+ success: false,
83
+ status: response.status,
84
+ error: \`HTTP \${response.status}: \${errorText.slice(0, 500)}\`
85
+ };
86
+ }
87
+
88
+ const data = await response.json().catch(() => ({}));
89
+ return {
90
+ success: true,
91
+ data
92
+ };
93
+ } catch (err) {
94
+ return {
95
+ success: false,
96
+ error: err instanceof Error ? err.message : String(err)
97
+ };
98
+ }
99
+ }
100
+ `;
101
+ }).join('\n');
102
+
103
+ const indexJs = `// Native HTTP plugin for ${service.name}
104
+ // Auto-generated by Causyne PluginsFactory
105
+
106
+ ${toolExecutors}
107
+ `;
108
+
109
+ const readmeMd = `# ${service.name} Plugin
110
+
111
+ ${service.description}
112
+
113
+ ## Route Information
114
+ - **Kind**: Native HTTP Plugin (Token-lean, on-demand execution)
115
+ - **Capabilities Required**: \`${capabilities.join(', ')}\`
116
+ ${service.authEnvVar ? `- **Environment Variable**: Set \`${service.authEnvVar}\` for authentication.` : ''}
117
+
118
+ ## Security & Activation
119
+ By default, this plugin is created in a **disabled** state to allow code review.
120
+ To activate after reviewing the code:
121
+ \`\`\`bash
122
+ causyne plugins enable ${service.name}
123
+ \`\`\`
124
+ `;
125
+
126
+ return {
127
+ entryPoint: 'index.js',
128
+ files: [
129
+ { relativePath: 'plugin.json', content: JSON.stringify(manifest, null, 2) + '\n' },
130
+ { relativePath: 'index.js', content: indexJs },
131
+ { relativePath: 'README.md', content: readmeMd }
132
+ ]
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Generates scaffold files for a Native CLI Wrapper Plugin.
138
+ */
139
+ export function generateCliPluginScaffold(service: ServiceDescriptor): ScaffoldingPayload {
140
+ const capabilities = Array.from(new Set(['subprocess', ...(service.capabilities || [])]));
141
+ const primaryTool = service.tools[0] || {
142
+ name: 'run',
143
+ description: `Execute command for ${service.name}`,
144
+ parameters: { type: 'object', properties: {} }
145
+ };
146
+
147
+ const manifest = {
148
+ schemaVersion: 1,
149
+ name: service.name,
150
+ version: '1.0.0',
151
+ description: service.description || `Native CLI plugin for ${service.name}`,
152
+ capabilities,
153
+ tools: service.tools.map(tool => ({
154
+ name: tool.name,
155
+ description: tool.description,
156
+ parameters: tool.parameters,
157
+ entry: 'index.js',
158
+ export: tool.name === primaryTool.name ? 'execute' : tool.name,
159
+ timeoutMs: 45000
160
+ }))
161
+ };
162
+
163
+ const toolExecutors = service.tools.map(tool => {
164
+ const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
165
+ const binary = service.cliBinary || service.name;
166
+ const subcommand = tool.cliSubcommand ? ` ${tool.cliSubcommand}` : '';
167
+ return `
168
+ /**
169
+ * ${tool.description}
170
+ */
171
+ export async function ${fnName}(args = {}, context = {}) {
172
+ const { execFile } = await import('node:child_process');
173
+ const { promisify } = await import('node:util');
174
+ const execFileAsync = promisify(execFile);
175
+
176
+ const bin = ${JSON.stringify(binary)};
177
+ const cliArgs = [];
178
+ ${tool.cliSubcommand ? `cliArgs.push(${JSON.stringify(tool.cliSubcommand)});` : ''}
179
+
180
+ for (const [key, val] of Object.entries(args)) {
181
+ if (val === true) cliArgs.push(\`--\${key}\`);
182
+ else if (val !== false && val !== null && val !== undefined) {
183
+ cliArgs.push(\`--\${key}\`, String(val));
184
+ }
185
+ }
186
+
187
+ try {
188
+ const { stdout, stderr } = await execFileAsync(bin, cliArgs, {
189
+ timeout: 40000,
190
+ maxBuffer: 1024 * 1024,
191
+ cwd: context.workspaceRoot || process.cwd()
192
+ });
193
+
194
+ return {
195
+ success: true,
196
+ stdout: stdout.trim(),
197
+ stderr: stderr.trim()
198
+ };
199
+ } catch (err) {
200
+ return {
201
+ success: false,
202
+ error: err instanceof Error ? err.message : String(err)
203
+ };
204
+ }
205
+ }
206
+ `;
207
+ }).join('\n');
208
+
209
+ const indexJs = `// Native CLI wrapper plugin for ${service.name}
210
+ // Auto-generated by Causyne PluginsFactory
211
+
212
+ ${toolExecutors}
213
+ `;
214
+
215
+ const readmeMd = `# ${service.name} CLI Plugin
216
+
217
+ ${service.description}
218
+
219
+ ## Route Information
220
+ - **Kind**: Native CLI Plugin (Subprocess wrapper)
221
+ - **Binary**: \`${service.cliBinary || service.name}\`
222
+ - **Capabilities Required**: \`${capabilities.join(', ')}\`
223
+
224
+ ## Security & Activation
225
+ This plugin is created disabled. After verifying the source code:
226
+ \`\`\`bash
227
+ causyne plugins enable ${service.name}
228
+ \`\`\`
229
+ `;
230
+
231
+ return {
232
+ entryPoint: 'index.js',
233
+ files: [
234
+ { relativePath: 'plugin.json', content: JSON.stringify(manifest, null, 2) + '\n' },
235
+ { relativePath: 'index.js', content: indexJs },
236
+ { relativePath: 'README.md', content: readmeMd }
237
+ ]
238
+ };
239
+ }
240
+
241
+ /**
242
+ * Generates scaffold files for a Python Bridge Plugin.
243
+ * Uses a Node runner with subprocess capability piping JSON stdin/stdout to bridge.py.
244
+ */
245
+ export function generatePythonBridgeScaffold(service: ServiceDescriptor): ScaffoldingPayload {
246
+ const capabilities = Array.from(new Set(['subprocess', ...(service.capabilities || [])]));
247
+ const primaryTool = service.tools[0] || {
248
+ name: 'run_python',
249
+ description: `Execute Python workflow for ${service.name}`,
250
+ parameters: { type: 'object', properties: {} }
251
+ };
252
+
253
+ const manifest = {
254
+ schemaVersion: 1,
255
+ name: service.name,
256
+ version: '1.0.0',
257
+ description: service.description || `Python bridge plugin for ${service.name}`,
258
+ capabilities,
259
+ tools: service.tools.map(tool => ({
260
+ name: tool.name,
261
+ description: tool.description,
262
+ parameters: tool.parameters,
263
+ entry: 'index.js',
264
+ export: tool.name === primaryTool.name ? 'execute' : tool.name,
265
+ timeoutMs: 60000
266
+ }))
267
+ };
268
+
269
+ const toolExecutors = service.tools.map(tool => {
270
+ const fnName = tool.name === primaryTool.name ? 'execute' : tool.name;
271
+ const pythonMethod = tool.pythonMethod || tool.name;
272
+ return `
273
+ /**
274
+ * ${tool.description}
275
+ */
276
+ export async function ${fnName}(args = {}, context = {}) {
277
+ return invokePythonBridge(${JSON.stringify(pythonMethod)}, args, context);
278
+ }
279
+ `;
280
+ }).join('\n');
281
+
282
+ const indexJs = `// Python bridge wrapper for ${service.name}
283
+ // Auto-generated by Causyne PluginsFactory
284
+
285
+ import { spawn } from 'node:child_process';
286
+ import path from 'node:path';
287
+ import { fileURLToPath } from 'node:url';
288
+
289
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
290
+ const BRIDGE_SCRIPT = path.join(__dirname, 'bridge.py');
291
+
292
+ async function invokePythonBridge(action, args, context) {
293
+ const payload = JSON.stringify({
294
+ action,
295
+ args: args || {},
296
+ context: {
297
+ workspaceRoot: context.workspaceRoot || process.cwd()
298
+ }
299
+ });
300
+
301
+ return new Promise((resolve) => {
302
+ const child = spawn('python3', [BRIDGE_SCRIPT], {
303
+ stdio: ['pipe', 'pipe', 'pipe'],
304
+ env: { ...process.env, PYTHONUNBUFFERED: '1' }
305
+ });
306
+
307
+ let stdout = '';
308
+ let stderr = '';
309
+ let settled = false;
310
+
311
+ const finish = (val) => {
312
+ if (settled) return;
313
+ settled = true;
314
+ clearTimeout(timer);
315
+ resolve(val);
316
+ };
317
+
318
+ const timer = setTimeout(() => {
319
+ child.kill('SIGTERM');
320
+ finish({ success: false, error: 'Python bridge timed out after 55 seconds' });
321
+ }, 55000);
322
+
323
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
324
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
325
+
326
+ child.on('error', (err) => {
327
+ finish({
328
+ success: false,
329
+ error: \`Failed to spawn python3: \${err.message}. Ensure python3 is installed and in PATH.\`
330
+ });
331
+ });
332
+
333
+ child.on('close', (code) => {
334
+ if (code !== 0 && !stdout.trim()) {
335
+ finish({
336
+ success: false,
337
+ exitCode: code,
338
+ error: stderr.trim() || \`Python bridge exited with code \${code}\`
339
+ });
340
+ return;
341
+ }
342
+
343
+ try {
344
+ const parsed = JSON.parse(stdout.trim());
345
+ finish(parsed);
346
+ } catch (parseErr) {
347
+ finish({
348
+ success: code === 0,
349
+ rawOutput: stdout.trim(),
350
+ stderr: stderr.trim(),
351
+ parseError: parseErr.message
352
+ });
353
+ }
354
+ });
355
+
356
+ child.stdin.write(payload);
357
+ child.stdin.end();
358
+ });
359
+ }
360
+
361
+ ${toolExecutors}
362
+ `;
363
+
364
+ const pythonModule = service.pythonModule || service.name;
365
+ const bridgePy = `#!/usr/bin/env python3
366
+ # -*- coding: utf-8 -*-
367
+ """
368
+ Python Bridge for ${service.name}
369
+ Auto-generated by Causyne PluginsFactory
370
+
371
+ Communicates with Causyne Agent via JSON on stdin/stdout.
372
+ Provides on-demand buffer for ${pythonModule}.
373
+ """
374
+
375
+ import sys
376
+ import json
377
+ import traceback
378
+
379
+ def handle_request(payload):
380
+ action = payload.get("action", "")
381
+ args = payload.get("args", {})
382
+ context = payload.get("context", {})
383
+
384
+ # Dispatched action handler
385
+ try:
386
+ # Example: Import target python library safely
387
+ # import ${pythonModule}
388
+
389
+ result = {
390
+ "action": action,
391
+ "processed": True,
392
+ "args_echo": args,
393
+ "message": f"Successfully executed {action} via Python bridge."
394
+ }
395
+ return {"success": True, "result": result}
396
+ except Exception as exc:
397
+ return {
398
+ "success": False,
399
+ "error": str(exc),
400
+ "traceback": traceback.format_exc()
401
+ }
402
+
403
+ def main():
404
+ try:
405
+ raw_input = sys.stdin.read()
406
+ if not raw_input.strip():
407
+ payload = {}
408
+ else:
409
+ payload = json.loads(raw_input)
410
+
411
+ response = handle_request(payload)
412
+ print(json.dumps(response))
413
+ sys.stdout.flush()
414
+ except Exception as exc:
415
+ print(json.dumps({
416
+ "success": False,
417
+ "error": f"Fatal bridge exception: {str(exc)}",
418
+ "traceback": traceback.format_exc()
419
+ }))
420
+ sys.stdout.flush()
421
+ sys.exit(1)
422
+
423
+ if __name__ == "__main__":
424
+ main()
425
+ `;
426
+
427
+ const readmeMd = `# ${service.name} Python Bridge Plugin
428
+
429
+ ${service.description}
430
+
431
+ ## Route Information
432
+ - **Kind**: Python Bridge (Subprocess JSON buffer)
433
+ - **Python Module**: \`${pythonModule}\`
434
+ - **Capabilities Required**: \`${capabilities.join(', ')}\`
435
+
436
+ ## Prerequisites
437
+ Ensure Python 3 is installed:
438
+ \`\`\`bash
439
+ python3 --version
440
+ \`\`\`
441
+
442
+ ## Security & Activation
443
+ This plugin is created disabled. Review the code in \`bridge.py\` and \`index.js\`, then enable:
444
+ \`\`\`bash
445
+ causyne plugins enable ${service.name}
446
+ \`\`\`
447
+ `;
448
+
449
+ return {
450
+ entryPoint: 'index.js',
451
+ files: [
452
+ { relativePath: 'plugin.json', content: JSON.stringify(manifest, null, 2) + '\n' },
453
+ { relativePath: 'index.js', content: indexJs },
454
+ { relativePath: 'bridge.py', content: bridgePy },
455
+ { relativePath: 'README.md', content: readmeMd }
456
+ ]
457
+ };
458
+ }
459
+
460
+ /**
461
+ * Generates scaffold files for a standalone Stdio MCP Server.
462
+ * Lightweight, zero-external-dependency JSON-RPC 2.0 stdio server.
463
+ */
464
+ export function generateMcpServerScaffold(service: ServiceDescriptor): ScaffoldingPayload {
465
+ const serverName = `mcp-server-${service.name}`;
466
+ const packageJson = {
467
+ name: serverName,
468
+ version: '1.0.0',
469
+ type: 'module',
470
+ description: service.description || `MCP Server for ${service.name}`,
471
+ main: 'server.js',
472
+ scripts: {
473
+ start: 'node server.js'
474
+ }
475
+ };
476
+
477
+ const toolsListJson = JSON.stringify(
478
+ service.tools.map(tool => ({
479
+ name: tool.name,
480
+ description: tool.description,
481
+ inputSchema: tool.parameters
482
+ })),
483
+ null,
484
+ 2
485
+ );
486
+
487
+ const serverJs = `#!/usr/bin/env node
488
+ // MCP Server for ${service.name}
489
+ // Protocol: Model Context Protocol (JSON-RPC 2.0 stdio)
490
+ // Auto-generated by Causyne PluginsFactory
491
+
492
+ import readline from 'node:readline';
493
+
494
+ const TOOLS = ${toolsListJson};
495
+
496
+ const rl = readline.createInterface({
497
+ input: process.stdin,
498
+ output: process.stdout,
499
+ terminal: false
500
+ });
501
+
502
+ function send(message) {
503
+ process.stdout.write(JSON.stringify(message) + '\\n');
504
+ }
505
+
506
+ function handleRequest(request) {
507
+ const { id, method, params } = request;
508
+
509
+ switch (method) {
510
+ case 'initialize':
511
+ return {
512
+ id,
513
+ jsonrpc: '2.0',
514
+ result: {
515
+ protocolVersion: '2024-11-05',
516
+ capabilities: { tools: {} },
517
+ serverInfo: {
518
+ name: ${JSON.stringify(serverName)},
519
+ version: '1.0.0'
520
+ }
521
+ }
522
+ };
523
+
524
+ case 'notifications/initialized':
525
+ return null;
526
+
527
+ case 'ping':
528
+ return { id, jsonrpc: '2.0', result: {} };
529
+
530
+ case 'tools/list':
531
+ return {
532
+ id,
533
+ jsonrpc: '2.0',
534
+ result: { tools: TOOLS }
535
+ };
536
+
537
+ case 'tools/call': {
538
+ const toolName = params?.name;
539
+ const toolArgs = params?.arguments || {};
540
+ const found = TOOLS.find(t => t.name === toolName);
541
+
542
+ if (!found) {
543
+ return {
544
+ id,
545
+ jsonrpc: '2.0',
546
+ error: { code: -32601, message: \`Tool '\${toolName}' not found\` }
547
+ };
548
+ }
549
+
550
+ // Execute tool logic
551
+ const resultData = {
552
+ tool: toolName,
553
+ success: true,
554
+ echo: toolArgs,
555
+ timestamp: new Date().toISOString()
556
+ };
557
+
558
+ return {
559
+ id,
560
+ jsonrpc: '2.0',
561
+ result: {
562
+ content: [
563
+ {
564
+ type: 'text',
565
+ text: JSON.stringify(resultData, null, 2)
566
+ }
567
+ ]
568
+ }
569
+ };
570
+ }
571
+
572
+ default:
573
+ if (id !== undefined) {
574
+ return {
575
+ id,
576
+ jsonrpc: '2.0',
577
+ error: { code: -32601, message: \`Method '\${method}' not supported\` }
578
+ };
579
+ }
580
+ return null;
581
+ }
582
+ }
583
+
584
+ rl.on('line', (line) => {
585
+ const trimmed = line.trim();
586
+ if (!trimmed) return;
587
+ try {
588
+ const request = JSON.parse(trimmed);
589
+ const response = handleRequest(request);
590
+ if (response) send(response);
591
+ } catch (err) {
592
+ send({
593
+ jsonrpc: '2.0',
594
+ id: null,
595
+ error: { code: -32700, message: 'Parse error: ' + String(err) }
596
+ });
597
+ }
598
+ });
599
+ `;
600
+
601
+ const readmeMd = `# ${serverName}
602
+
603
+ ${service.description}
604
+
605
+ ## Route Information
606
+ - **Kind**: Model Context Protocol (MCP) stdio Server
607
+ - **Protocol**: JSON-RPC 2.0 over standard I/O
608
+ - **Tools Supported**: ${service.tools.map(t => t.name).join(', ')}
609
+
610
+ ## Token Footprint Note
611
+ MCP servers consume additional tokens per turn due to persistent JSON-RPC schema envelopes.
612
+ Where feasible, prefer native plugins or Python bridges for higher token efficiency.
613
+
614
+ ## Registration & Grant
615
+ In Causyne Agent, register and review this server:
616
+ \`\`\`bash
617
+ causyne mcp add ${service.name} node ~/.causyne/mcp-servers/${service.name}/server.js
618
+ causyne mcp grant ${service.name}
619
+ \`\`\`
620
+ `;
621
+
622
+ return {
623
+ entryPoint: 'server.js',
624
+ files: [
625
+ { relativePath: 'package.json', content: JSON.stringify(packageJson, null, 2) + '\n' },
626
+ { relativePath: 'server.js', content: serverJs },
627
+ { relativePath: 'README.md', content: readmeMd }
628
+ ]
629
+ };
630
+ }
631
+
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Types and interfaces for PluginsFactory.
3
+ *
4
+ * PluginsFactory empowers Causyne Agent to generate custom plugins, Python bridges,
5
+ * or MCP servers when a requested service/integration does not yet exist.
6
+ *
7
+ * Route Strategy:
8
+ * 1. Native Plugin (HTTP/CLI): Leanest token footprint, lowest cost.
9
+ * 2. Python Bridge: Spawns Python subprocess with JSON protocol for Python-only SDKs.
10
+ * 3. MCP Server: Used when a service strictly permits only MCP or the user explicitly asks for it.
11
+ */
12
+ export {};