@causyne/agent 1.20.38 → 1.20.41

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