@causyne/agent 1.20.36 → 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.
- package/LICENSE +1 -1
- package/package.json +1 -1
- package/src/decisionPolicy.js +1 -1
- package/src/decisionPolicy.ts +1 -1
- package/src/plugins/pluginsFactory.js +4 -0
- package/src/plugins/pluginsFactory.ts +6 -0
- package/src/pluginsFactory/costEstimate.js +89 -0
- package/src/pluginsFactory/costEstimate.ts +110 -0
- package/src/pluginsFactory/discovery.js +97 -0
- package/src/pluginsFactory/discovery.ts +114 -0
- package/src/pluginsFactory/index.js +9 -0
- package/src/pluginsFactory/index.ts +11 -0
- package/src/pluginsFactory/pluginsFactory.js +250 -0
- package/src/pluginsFactory/pluginsFactory.ts +302 -0
- package/src/pluginsFactory/strategy.js +93 -0
- package/src/pluginsFactory/strategy.ts +106 -0
- package/src/pluginsFactory/templates.js +592 -0
- package/src/pluginsFactory/templates.ts +631 -0
- package/src/pluginsFactory/types.js +12 -0
- package/src/pluginsFactory/types.ts +107 -0
- package/src/stallGuard.js +1 -0
- package/src/stallGuard.ts +1 -0
- package/src/toolPacks.js +1 -0
- package/src/toolPacks.ts +1 -0
- package/src/tools/pluginsFactory.js +202 -0
- package/src/tools/pluginsFactory.ts +246 -0
- package/src/tools/registry.js +2 -1
- package/src/tools/sysRun.js +22 -6
- package/src/tools/sysRun.ts +23 -6
- package/src/toolsList.js +1 -0
- package/src/toolsList.ts +1 -0
- package/src/tui/chatRenderer.js +5 -4
- package/src/tui/homeView.js +0 -1
- package/src/tui/homeView.ts +0 -1
- package/src/tui/markdownMath.js +250 -0
- package/src/tui/markdownMath.ts +263 -0
- package/src/tui/messageActionPlacement.js +79 -8
- package/src/tui/messageActionPlacement.ts +102 -9
- package/src/tui/messageInteraction.js +43 -9
- package/src/tui/messageInteraction.ts +51 -17
- package/src/tui/overlay.js +191 -192
- package/src/tui/overlay.ts +320 -0
- package/src/tui/prompt.js +4 -1
- package/src/tui/stageSurface.js +4 -1
- package/src/tui/text.js +204 -208
- package/src/tui/text.ts +360 -0
- package/src/tui/toolOutputNormalizer.js +3 -1
- package/src/tui/toolOutputNormalizer.ts +3 -1
- package/src/tui/turnRail.js +11 -1
- package/src/tui/turnRail.ts +11 -1
- package/src/tui/text.d.ts +0 -7
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PluginsFactory — Autonomous Custom Integration Engine for Causyne Agent.
|
|
3
|
+
*
|
|
4
|
+
* Engineered in strict TypeScript.
|
|
5
|
+
*
|
|
6
|
+
* Responsibilities:
|
|
7
|
+
* 1. Evaluate missing integration needs and assess the most token-lean and cost-effective route:
|
|
8
|
+
* - Route 1 (Native HTTP/CLI): Lowest token consumption and immediate on-demand execution.
|
|
9
|
+
* - Route 2 (Python Bridge): On-demand subprocess buffer for Python-only libraries.
|
|
10
|
+
* - Route 3 (MCP Server): Standard protocol for MCP-only services or when requested by user.
|
|
11
|
+
* 2. Enforce token transparency: Disclose MCP token footprint overhead honestly, while completely
|
|
12
|
+
* honoring user preferences when MCP is chosen.
|
|
13
|
+
* 3. Scaffold production-grade plugins and servers in ~/.causyne/ (never shipped inside the npm package).
|
|
14
|
+
* 4. Maintain security invariants: Plugins are created disabled; MCP servers are created ungranted;
|
|
15
|
+
* SHA-256 integrity digests are calculated and recorded.
|
|
16
|
+
*/
|
|
17
|
+
import crypto from 'node:crypto';
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { causyneHome } from '../utils/paths.js';
|
|
21
|
+
import { assessRoute } from './strategy.js';
|
|
22
|
+
import { generateCliPluginScaffold, generateHttpPluginScaffold, generateMcpServerScaffold, generatePythonBridgeScaffold } from './templates.js';
|
|
23
|
+
const NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
24
|
+
/**
|
|
25
|
+
* Computes the exact SHA-256 directory digest matching Causyne's pluginManager.
|
|
26
|
+
*/
|
|
27
|
+
export function computePluginDirectoryDigest(directory) {
|
|
28
|
+
const files = [];
|
|
29
|
+
const visit = (current) => {
|
|
30
|
+
const entries = fs.readdirSync(current, { withFileTypes: true })
|
|
31
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
32
|
+
for (const entry of entries) {
|
|
33
|
+
const absolute = path.join(current, entry.name);
|
|
34
|
+
const stat = fs.lstatSync(absolute);
|
|
35
|
+
if (stat.isSymbolicLink()) {
|
|
36
|
+
throw new Error(`Plugin file must not be a symlink: ${entry.name}`);
|
|
37
|
+
}
|
|
38
|
+
if (stat.isDirectory()) {
|
|
39
|
+
visit(absolute);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (stat.isFile()) {
|
|
43
|
+
files.push({ absolute, relative: path.relative(directory, absolute) });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
visit(directory);
|
|
48
|
+
const digest = crypto.createHash('sha256');
|
|
49
|
+
for (const file of files) {
|
|
50
|
+
digest.update(file.relative);
|
|
51
|
+
digest.update('\0');
|
|
52
|
+
digest.update(fs.readFileSync(file.absolute));
|
|
53
|
+
digest.update('\0');
|
|
54
|
+
}
|
|
55
|
+
return digest.digest('hex');
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* PluginsFactory core engine.
|
|
59
|
+
*/
|
|
60
|
+
export class PluginsFactory {
|
|
61
|
+
pluginsRoot;
|
|
62
|
+
mcpServersRoot;
|
|
63
|
+
constructor(options = {}) {
|
|
64
|
+
const baseHome = causyneHome();
|
|
65
|
+
this.pluginsRoot = options.pluginsDir
|
|
66
|
+
? path.resolve(options.pluginsDir)
|
|
67
|
+
: path.join(baseHome, 'plugins');
|
|
68
|
+
this.mcpServersRoot = options.mcpServersDir
|
|
69
|
+
? path.resolve(options.mcpServersDir)
|
|
70
|
+
: path.join(baseHome, 'mcp-servers');
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Evaluates the service and generates an actionable route proposal with cost estimates.
|
|
74
|
+
*/
|
|
75
|
+
assess(service, userPreference) {
|
|
76
|
+
return assessRoute(service, userPreference);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Scaffolds the integration into ~/.causyne/plugins or ~/.causyne/mcp-servers.
|
|
80
|
+
*/
|
|
81
|
+
async scaffold(proposal, options = {}) {
|
|
82
|
+
const service = proposal.service;
|
|
83
|
+
const normalizedName = service.name.trim().toLowerCase();
|
|
84
|
+
if (!NAME_PATTERN.test(normalizedName)) {
|
|
85
|
+
return {
|
|
86
|
+
success: false,
|
|
87
|
+
route: proposal.recommendedRoute,
|
|
88
|
+
targetDirectory: '',
|
|
89
|
+
createdFiles: [],
|
|
90
|
+
instructions: '',
|
|
91
|
+
error: `Invalid service name "${service.name}". Must match ^[a-z0-9][a-z0-9-]{0,63}$`
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
const route = proposal.userConfirmedRoute ?? proposal.recommendedRoute;
|
|
95
|
+
const isMcp = route === 'mcp_server';
|
|
96
|
+
const baseDir = options.baseDir
|
|
97
|
+
? path.resolve(options.baseDir)
|
|
98
|
+
: isMcp
|
|
99
|
+
? this.mcpServersRoot
|
|
100
|
+
: this.pluginsRoot;
|
|
101
|
+
const targetDir = path.join(baseDir, normalizedName);
|
|
102
|
+
// Path containment check: ensure targetDir cannot escape baseDir
|
|
103
|
+
const resolvedBase = path.resolve(baseDir);
|
|
104
|
+
const resolvedTarget = path.resolve(targetDir);
|
|
105
|
+
if (!resolvedTarget.startsWith(resolvedBase + path.sep)) {
|
|
106
|
+
return {
|
|
107
|
+
success: false,
|
|
108
|
+
route,
|
|
109
|
+
targetDirectory: targetDir,
|
|
110
|
+
createdFiles: [],
|
|
111
|
+
instructions: '',
|
|
112
|
+
error: `Target path escapes directory boundary: ${targetDir}`
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
if (fs.existsSync(targetDir) && !options.force) {
|
|
116
|
+
return {
|
|
117
|
+
success: false,
|
|
118
|
+
route,
|
|
119
|
+
targetDirectory: targetDir,
|
|
120
|
+
createdFiles: [],
|
|
121
|
+
instructions: '',
|
|
122
|
+
error: `Directory already exists: ${targetDir}. Use force: true to overwrite.`
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
// Select scaffolding payload generator based on route
|
|
126
|
+
let payload;
|
|
127
|
+
if (route === 'native_plugin') {
|
|
128
|
+
if (service.serviceKind === 'cli' || service.cliBinary) {
|
|
129
|
+
payload = generateCliPluginScaffold(service);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
payload = generateHttpPluginScaffold(service);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
else if (route === 'python_bridge') {
|
|
136
|
+
payload = generatePythonBridgeScaffold(service);
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
payload = generateMcpServerScaffold(service);
|
|
140
|
+
}
|
|
141
|
+
if (options.dryRun) {
|
|
142
|
+
return {
|
|
143
|
+
success: true,
|
|
144
|
+
route,
|
|
145
|
+
targetDirectory: targetDir,
|
|
146
|
+
createdFiles: payload.files.map(f => f.relativePath),
|
|
147
|
+
instructions: `[Dry Run] Scaffolding plan ready for ${service.name} at ${targetDir}`
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
// Write files to target directory
|
|
151
|
+
fs.mkdirSync(targetDir, { recursive: true, mode: 0o700 });
|
|
152
|
+
const createdFiles = [];
|
|
153
|
+
for (const file of payload.files) {
|
|
154
|
+
const filePath = path.join(targetDir, file.relativePath);
|
|
155
|
+
const fileDir = path.dirname(filePath);
|
|
156
|
+
if (!fs.existsSync(fileDir)) {
|
|
157
|
+
fs.mkdirSync(fileDir, { recursive: true, mode: 0o700 });
|
|
158
|
+
}
|
|
159
|
+
fs.writeFileSync(filePath, file.content, { encoding: 'utf8', mode: 0o600 });
|
|
160
|
+
createdFiles.push(file.relativePath);
|
|
161
|
+
}
|
|
162
|
+
let digest;
|
|
163
|
+
let instructions;
|
|
164
|
+
if (!isMcp) {
|
|
165
|
+
// Calculate plugin digest
|
|
166
|
+
digest = computePluginDirectoryDigest(targetDir);
|
|
167
|
+
// Record disabled state in state.json
|
|
168
|
+
this.recordPluginState(normalizedName, digest);
|
|
169
|
+
instructions = [
|
|
170
|
+
`Custom plugin '${normalizedName}' successfully scaffolded at: ${targetDir}`,
|
|
171
|
+
`Kind: ${route === 'python_bridge' ? 'Python Bridge Plugin' : 'Native Plugin'}`,
|
|
172
|
+
`Digest (SHA-256): ${digest}`,
|
|
173
|
+
`Security Status: DISABLED (Review source files before enabling)`,
|
|
174
|
+
'',
|
|
175
|
+
`To activate after review:`,
|
|
176
|
+
` causyne plugins enable ${normalizedName}`
|
|
177
|
+
].join('\n');
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
instructions = [
|
|
181
|
+
`MCP Server '${normalizedName}' successfully scaffolded at: ${targetDir}`,
|
|
182
|
+
`Kind: Model Context Protocol stdio server`,
|
|
183
|
+
`Security Status: UNGRANTED (Review source files before granting)`,
|
|
184
|
+
'',
|
|
185
|
+
`To register and grant:`,
|
|
186
|
+
` causyne mcp add ${normalizedName} node ${path.join(targetDir, 'server.js')}`,
|
|
187
|
+
` causyne mcp grant ${normalizedName}`
|
|
188
|
+
].join('\n');
|
|
189
|
+
}
|
|
190
|
+
const result = {
|
|
191
|
+
success: true,
|
|
192
|
+
route,
|
|
193
|
+
targetDirectory: targetDir,
|
|
194
|
+
createdFiles,
|
|
195
|
+
instructions
|
|
196
|
+
};
|
|
197
|
+
if (digest !== undefined) {
|
|
198
|
+
result.digest = digest;
|
|
199
|
+
}
|
|
200
|
+
return result;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Ensures state.json records the newly scaffolded plugin as disabled.
|
|
204
|
+
*/
|
|
205
|
+
recordPluginState(pluginName, digest) {
|
|
206
|
+
try {
|
|
207
|
+
const stateFile = path.join(this.pluginsRoot, 'state.json');
|
|
208
|
+
let state = {
|
|
209
|
+
version: 1,
|
|
210
|
+
plugins: {}
|
|
211
|
+
};
|
|
212
|
+
if (fs.existsSync(stateFile)) {
|
|
213
|
+
try {
|
|
214
|
+
const raw = fs.readFileSync(stateFile, 'utf8');
|
|
215
|
+
const parsed = JSON.parse(raw);
|
|
216
|
+
if (parsed && typeof parsed === 'object') {
|
|
217
|
+
state = { version: 1, plugins: parsed.plugins || {} };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
// ignore corrupted state
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
state.plugins[pluginName] = {
|
|
225
|
+
enabled: false,
|
|
226
|
+
digest
|
|
227
|
+
};
|
|
228
|
+
const tmp = `${stateFile}.tmp_${process.pid}_${Date.now()}`;
|
|
229
|
+
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { mode: 0o600 });
|
|
230
|
+
fs.renameSync(tmp, stateFile);
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
// Graceful fallback if plugins directory is mock or read-only
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Top-level convenience function for evaluating route.
|
|
239
|
+
*/
|
|
240
|
+
export function assessPluginRoute(service, userPreference) {
|
|
241
|
+
const factory = new PluginsFactory();
|
|
242
|
+
return factory.assess(service, userPreference);
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Top-level convenience function for scaffolding.
|
|
246
|
+
*/
|
|
247
|
+
export async function scaffoldPlugin(proposal, options) {
|
|
248
|
+
const factory = new PluginsFactory();
|
|
249
|
+
return factory.scaffold(proposal, options);
|
|
250
|
+
}
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PluginsFactory — Autonomous Custom Integration Engine for Causyne Agent.
|
|
3
|
+
*
|
|
4
|
+
* Engineered in strict TypeScript.
|
|
5
|
+
*
|
|
6
|
+
* Responsibilities:
|
|
7
|
+
* 1. Evaluate missing integration needs and assess the most token-lean and cost-effective route:
|
|
8
|
+
* - Route 1 (Native HTTP/CLI): Lowest token consumption and immediate on-demand execution.
|
|
9
|
+
* - Route 2 (Python Bridge): On-demand subprocess buffer for Python-only libraries.
|
|
10
|
+
* - Route 3 (MCP Server): Standard protocol for MCP-only services or when requested by user.
|
|
11
|
+
* 2. Enforce token transparency: Disclose MCP token footprint overhead honestly, while completely
|
|
12
|
+
* honoring user preferences when MCP is chosen.
|
|
13
|
+
* 3. Scaffold production-grade plugins and servers in ~/.causyne/ (never shipped inside the npm package).
|
|
14
|
+
* 4. Maintain security invariants: Plugins are created disabled; MCP servers are created ungranted;
|
|
15
|
+
* SHA-256 integrity digests are calculated and recorded.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import crypto from 'node:crypto';
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { causyneHome } from '../utils/paths.js';
|
|
22
|
+
import { assessRoute } from './strategy.js';
|
|
23
|
+
import {
|
|
24
|
+
generateCliPluginScaffold,
|
|
25
|
+
generateHttpPluginScaffold,
|
|
26
|
+
generateMcpServerScaffold,
|
|
27
|
+
generatePythonBridgeScaffold
|
|
28
|
+
} from './templates.js';
|
|
29
|
+
import type {
|
|
30
|
+
FactoryRouteProposal,
|
|
31
|
+
PluginFactoryOptions,
|
|
32
|
+
RouteKind,
|
|
33
|
+
ScaffoldOptions,
|
|
34
|
+
ScaffoldResult,
|
|
35
|
+
ServiceDescriptor
|
|
36
|
+
} from './types.js';
|
|
37
|
+
|
|
38
|
+
const NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Computes the exact SHA-256 directory digest matching Causyne's pluginManager.
|
|
42
|
+
*/
|
|
43
|
+
export function computePluginDirectoryDigest(directory: string): string {
|
|
44
|
+
interface FileEntry {
|
|
45
|
+
absolute: string;
|
|
46
|
+
relative: string;
|
|
47
|
+
}
|
|
48
|
+
const files: FileEntry[] = [];
|
|
49
|
+
|
|
50
|
+
const visit = (current: string) => {
|
|
51
|
+
const entries = fs.readdirSync(current, { withFileTypes: true })
|
|
52
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
53
|
+
for (const entry of entries) {
|
|
54
|
+
const absolute = path.join(current, entry.name);
|
|
55
|
+
const stat = fs.lstatSync(absolute);
|
|
56
|
+
if (stat.isSymbolicLink()) {
|
|
57
|
+
throw new Error(`Plugin file must not be a symlink: ${entry.name}`);
|
|
58
|
+
}
|
|
59
|
+
if (stat.isDirectory()) {
|
|
60
|
+
visit(absolute);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (stat.isFile()) {
|
|
64
|
+
files.push({ absolute, relative: path.relative(directory, absolute) });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
visit(directory);
|
|
70
|
+
|
|
71
|
+
const digest = crypto.createHash('sha256');
|
|
72
|
+
for (const file of files) {
|
|
73
|
+
digest.update(file.relative);
|
|
74
|
+
digest.update('\0');
|
|
75
|
+
digest.update(fs.readFileSync(file.absolute));
|
|
76
|
+
digest.update('\0');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return digest.digest('hex');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* PluginsFactory core engine.
|
|
84
|
+
*/
|
|
85
|
+
export class PluginsFactory {
|
|
86
|
+
private readonly pluginsRoot: string;
|
|
87
|
+
private readonly mcpServersRoot: string;
|
|
88
|
+
|
|
89
|
+
constructor(options: PluginFactoryOptions = {}) {
|
|
90
|
+
const baseHome = causyneHome();
|
|
91
|
+
this.pluginsRoot = options.pluginsDir
|
|
92
|
+
? path.resolve(options.pluginsDir)
|
|
93
|
+
: path.join(baseHome, 'plugins');
|
|
94
|
+
this.mcpServersRoot = options.mcpServersDir
|
|
95
|
+
? path.resolve(options.mcpServersDir)
|
|
96
|
+
: path.join(baseHome, 'mcp-servers');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Evaluates the service and generates an actionable route proposal with cost estimates.
|
|
101
|
+
*/
|
|
102
|
+
assess(service: ServiceDescriptor, userPreference?: RouteKind): FactoryRouteProposal {
|
|
103
|
+
return assessRoute(service, userPreference);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Scaffolds the integration into ~/.causyne/plugins or ~/.causyne/mcp-servers.
|
|
108
|
+
*/
|
|
109
|
+
async scaffold(
|
|
110
|
+
proposal: FactoryRouteProposal,
|
|
111
|
+
options: ScaffoldOptions = {}
|
|
112
|
+
): Promise<ScaffoldResult> {
|
|
113
|
+
const service = proposal.service;
|
|
114
|
+
const normalizedName = service.name.trim().toLowerCase();
|
|
115
|
+
|
|
116
|
+
if (!NAME_PATTERN.test(normalizedName)) {
|
|
117
|
+
return {
|
|
118
|
+
success: false,
|
|
119
|
+
route: proposal.recommendedRoute,
|
|
120
|
+
targetDirectory: '',
|
|
121
|
+
createdFiles: [],
|
|
122
|
+
instructions: '',
|
|
123
|
+
error: `Invalid service name "${service.name}". Must match ^[a-z0-9][a-z0-9-]{0,63}$`
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const route = proposal.userConfirmedRoute ?? proposal.recommendedRoute;
|
|
128
|
+
const isMcp = route === 'mcp_server';
|
|
129
|
+
|
|
130
|
+
const baseDir = options.baseDir
|
|
131
|
+
? path.resolve(options.baseDir)
|
|
132
|
+
: isMcp
|
|
133
|
+
? this.mcpServersRoot
|
|
134
|
+
: this.pluginsRoot;
|
|
135
|
+
|
|
136
|
+
const targetDir = path.join(baseDir, normalizedName);
|
|
137
|
+
|
|
138
|
+
// Path containment check: ensure targetDir cannot escape baseDir
|
|
139
|
+
const resolvedBase = path.resolve(baseDir);
|
|
140
|
+
const resolvedTarget = path.resolve(targetDir);
|
|
141
|
+
if (!resolvedTarget.startsWith(resolvedBase + path.sep)) {
|
|
142
|
+
return {
|
|
143
|
+
success: false,
|
|
144
|
+
route,
|
|
145
|
+
targetDirectory: targetDir,
|
|
146
|
+
createdFiles: [],
|
|
147
|
+
instructions: '',
|
|
148
|
+
error: `Target path escapes directory boundary: ${targetDir}`
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (fs.existsSync(targetDir) && !options.force) {
|
|
153
|
+
return {
|
|
154
|
+
success: false,
|
|
155
|
+
route,
|
|
156
|
+
targetDirectory: targetDir,
|
|
157
|
+
createdFiles: [],
|
|
158
|
+
instructions: '',
|
|
159
|
+
error: `Directory already exists: ${targetDir}. Use force: true to overwrite.`
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Select scaffolding payload generator based on route
|
|
164
|
+
let payload;
|
|
165
|
+
if (route === 'native_plugin') {
|
|
166
|
+
if (service.serviceKind === 'cli' || service.cliBinary) {
|
|
167
|
+
payload = generateCliPluginScaffold(service);
|
|
168
|
+
} else {
|
|
169
|
+
payload = generateHttpPluginScaffold(service);
|
|
170
|
+
}
|
|
171
|
+
} else if (route === 'python_bridge') {
|
|
172
|
+
payload = generatePythonBridgeScaffold(service);
|
|
173
|
+
} else {
|
|
174
|
+
payload = generateMcpServerScaffold(service);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (options.dryRun) {
|
|
178
|
+
return {
|
|
179
|
+
success: true,
|
|
180
|
+
route,
|
|
181
|
+
targetDirectory: targetDir,
|
|
182
|
+
createdFiles: payload.files.map(f => f.relativePath),
|
|
183
|
+
instructions: `[Dry Run] Scaffolding plan ready for ${service.name} at ${targetDir}`
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Write files to target directory
|
|
188
|
+
fs.mkdirSync(targetDir, { recursive: true, mode: 0o700 });
|
|
189
|
+
const createdFiles: string[] = [];
|
|
190
|
+
|
|
191
|
+
for (const file of payload.files) {
|
|
192
|
+
const filePath = path.join(targetDir, file.relativePath);
|
|
193
|
+
const fileDir = path.dirname(filePath);
|
|
194
|
+
if (!fs.existsSync(fileDir)) {
|
|
195
|
+
fs.mkdirSync(fileDir, { recursive: true, mode: 0o700 });
|
|
196
|
+
}
|
|
197
|
+
fs.writeFileSync(filePath, file.content, { encoding: 'utf8', mode: 0o600 });
|
|
198
|
+
createdFiles.push(file.relativePath);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
let digest: string | undefined;
|
|
202
|
+
let instructions: string;
|
|
203
|
+
|
|
204
|
+
if (!isMcp) {
|
|
205
|
+
// Calculate plugin digest
|
|
206
|
+
digest = computePluginDirectoryDigest(targetDir);
|
|
207
|
+
|
|
208
|
+
// Record disabled state in state.json
|
|
209
|
+
this.recordPluginState(normalizedName, digest);
|
|
210
|
+
|
|
211
|
+
instructions = [
|
|
212
|
+
`Custom plugin '${normalizedName}' successfully scaffolded at: ${targetDir}`,
|
|
213
|
+
`Kind: ${route === 'python_bridge' ? 'Python Bridge Plugin' : 'Native Plugin'}`,
|
|
214
|
+
`Digest (SHA-256): ${digest}`,
|
|
215
|
+
`Security Status: DISABLED (Review source files before enabling)`,
|
|
216
|
+
'',
|
|
217
|
+
`To activate after review:`,
|
|
218
|
+
` causyne plugins enable ${normalizedName}`
|
|
219
|
+
].join('\n');
|
|
220
|
+
} else {
|
|
221
|
+
instructions = [
|
|
222
|
+
`MCP Server '${normalizedName}' successfully scaffolded at: ${targetDir}`,
|
|
223
|
+
`Kind: Model Context Protocol stdio server`,
|
|
224
|
+
`Security Status: UNGRANTED (Review source files before granting)`,
|
|
225
|
+
'',
|
|
226
|
+
`To register and grant:`,
|
|
227
|
+
` causyne mcp add ${normalizedName} node ${path.join(targetDir, 'server.js')}`,
|
|
228
|
+
` causyne mcp grant ${normalizedName}`
|
|
229
|
+
].join('\n');
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const result: ScaffoldResult = {
|
|
233
|
+
success: true,
|
|
234
|
+
route,
|
|
235
|
+
targetDirectory: targetDir,
|
|
236
|
+
createdFiles,
|
|
237
|
+
instructions
|
|
238
|
+
};
|
|
239
|
+
if (digest !== undefined) {
|
|
240
|
+
result.digest = digest;
|
|
241
|
+
}
|
|
242
|
+
return result;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Ensures state.json records the newly scaffolded plugin as disabled.
|
|
247
|
+
*/
|
|
248
|
+
private recordPluginState(pluginName: string, digest: string): void {
|
|
249
|
+
try {
|
|
250
|
+
const stateFile = path.join(this.pluginsRoot, 'state.json');
|
|
251
|
+
let state: { version: number; plugins: Record<string, { enabled: boolean; digest?: string }> } = {
|
|
252
|
+
version: 1,
|
|
253
|
+
plugins: {}
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
if (fs.existsSync(stateFile)) {
|
|
257
|
+
try {
|
|
258
|
+
const raw = fs.readFileSync(stateFile, 'utf8');
|
|
259
|
+
const parsed = JSON.parse(raw);
|
|
260
|
+
if (parsed && typeof parsed === 'object') {
|
|
261
|
+
state = { version: 1, plugins: parsed.plugins || {} };
|
|
262
|
+
}
|
|
263
|
+
} catch {
|
|
264
|
+
// ignore corrupted state
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
state.plugins[pluginName] = {
|
|
269
|
+
enabled: false,
|
|
270
|
+
digest
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
const tmp = `${stateFile}.tmp_${process.pid}_${Date.now()}`;
|
|
274
|
+
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { mode: 0o600 });
|
|
275
|
+
fs.renameSync(tmp, stateFile);
|
|
276
|
+
} catch {
|
|
277
|
+
// Graceful fallback if plugins directory is mock or read-only
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Top-level convenience function for evaluating route.
|
|
284
|
+
*/
|
|
285
|
+
export function assessPluginRoute(
|
|
286
|
+
service: ServiceDescriptor,
|
|
287
|
+
userPreference?: RouteKind
|
|
288
|
+
): FactoryRouteProposal {
|
|
289
|
+
const factory = new PluginsFactory();
|
|
290
|
+
return factory.assess(service, userPreference);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Top-level convenience function for scaffolding.
|
|
295
|
+
*/
|
|
296
|
+
export async function scaffoldPlugin(
|
|
297
|
+
proposal: FactoryRouteProposal,
|
|
298
|
+
options?: ScaffoldOptions
|
|
299
|
+
): Promise<ScaffoldResult> {
|
|
300
|
+
const factory = new PluginsFactory();
|
|
301
|
+
return factory.scaffold(proposal, options);
|
|
302
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Route Selection Strategy for PluginsFactory.
|
|
3
|
+
*
|
|
4
|
+
* Implements deterministic route assessment prioritizing token efficiency and cost:
|
|
5
|
+
* 1. Check existing coverage: Built-in tools, installed plugins, configured MCP servers.
|
|
6
|
+
* 2. Honor explicit user preference immediately without unnecessary friction.
|
|
7
|
+
* 3. Route 1: Native Plugin (HTTP/CLI) - Leanest token footprint, lowest cost.
|
|
8
|
+
* 4. Route 2: Python Bridge - Lightweight on-demand buffer for Python-only libraries.
|
|
9
|
+
* 5. Route 3: MCP Server - Used when service is MCP-only or user explicitly requests it.
|
|
10
|
+
*/
|
|
11
|
+
import { estimateServiceCosts, formatMcpDisclosure } from './costEstimate.js';
|
|
12
|
+
import { findExistingCapability } from './discovery.js';
|
|
13
|
+
const PYTHON_KEYWORDS = [
|
|
14
|
+
'python',
|
|
15
|
+
'scipy',
|
|
16
|
+
'numpy',
|
|
17
|
+
'pandas',
|
|
18
|
+
'torch',
|
|
19
|
+
'pytorch',
|
|
20
|
+
'tensorflow',
|
|
21
|
+
'keras',
|
|
22
|
+
'blender',
|
|
23
|
+
'resolve',
|
|
24
|
+
'bpy',
|
|
25
|
+
'da_vinci',
|
|
26
|
+
'sympy',
|
|
27
|
+
'nltk',
|
|
28
|
+
'spacy',
|
|
29
|
+
'huggingface'
|
|
30
|
+
];
|
|
31
|
+
function isPythonSpecific(service) {
|
|
32
|
+
if (service.serviceKind === 'python_sdk')
|
|
33
|
+
return true;
|
|
34
|
+
if (service.pythonModule && service.pythonModule.trim())
|
|
35
|
+
return true;
|
|
36
|
+
const nameLower = service.name.toLowerCase();
|
|
37
|
+
const descLower = (service.description || '').toLowerCase();
|
|
38
|
+
return PYTHON_KEYWORDS.some(kw => nameLower.includes(kw) || descLower.includes(kw));
|
|
39
|
+
}
|
|
40
|
+
export function assessRoute(service, userPreference) {
|
|
41
|
+
const costComparison = estimateServiceCosts(service);
|
|
42
|
+
const existingCapability = findExistingCapability(service.name);
|
|
43
|
+
// 1. User Preference Override
|
|
44
|
+
const chosenRoute = userPreference ?? service.userPreferredRoute;
|
|
45
|
+
if (chosenRoute) {
|
|
46
|
+
const isMcp = chosenRoute === 'mcp_server';
|
|
47
|
+
const proposal = {
|
|
48
|
+
service,
|
|
49
|
+
recommendedRoute: chosenRoute,
|
|
50
|
+
reason: `Honoring user explicit preference for route '${chosenRoute}'.`,
|
|
51
|
+
costComparison,
|
|
52
|
+
userConsentRequired: false,
|
|
53
|
+
userConfirmedRoute: chosenRoute,
|
|
54
|
+
existingCapability: existingCapability.covered ? existingCapability : undefined
|
|
55
|
+
};
|
|
56
|
+
if (isMcp) {
|
|
57
|
+
proposal.mcpDisclosure = formatMcpDisclosure(service.name, costComparison);
|
|
58
|
+
}
|
|
59
|
+
return proposal;
|
|
60
|
+
}
|
|
61
|
+
// 2. Python SDK Route (Bridge Buffer)
|
|
62
|
+
if (isPythonSpecific(service)) {
|
|
63
|
+
return {
|
|
64
|
+
service,
|
|
65
|
+
recommendedRoute: 'python_bridge',
|
|
66
|
+
reason: 'Service depends on Python SDK or specialized scientific/creative modules. A Python bridge provides an on-demand subprocess buffer without full MCP overhead.',
|
|
67
|
+
costComparison,
|
|
68
|
+
userConsentRequired: false,
|
|
69
|
+
existingCapability: existingCapability.covered ? existingCapability : undefined
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
// 3. MCP-Only Service Route
|
|
73
|
+
if (service.serviceKind === 'mcp_only') {
|
|
74
|
+
return {
|
|
75
|
+
service,
|
|
76
|
+
recommendedRoute: 'mcp_server',
|
|
77
|
+
reason: 'Service exclusively exposes an MCP endpoint or protocol. Recommending MCP server scaffold with token overhead disclosure.',
|
|
78
|
+
costComparison,
|
|
79
|
+
mcpDisclosure: formatMcpDisclosure(service.name, costComparison),
|
|
80
|
+
userConsentRequired: true,
|
|
81
|
+
existingCapability: existingCapability.covered ? existingCapability : undefined
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
// 4. Default / Native Plugin Route (HTTP API or CLI)
|
|
85
|
+
return {
|
|
86
|
+
service,
|
|
87
|
+
recommendedRoute: 'native_plugin',
|
|
88
|
+
reason: 'Service supports HTTP/REST API or CLI interface. Native plugin is selected as the most token-lean and cost-effective route.',
|
|
89
|
+
costComparison,
|
|
90
|
+
userConsentRequired: false,
|
|
91
|
+
existingCapability: existingCapability.covered ? existingCapability : undefined
|
|
92
|
+
};
|
|
93
|
+
}
|