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