@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,255 @@
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
+ ` (or in chat: /plugins enable ${normalizedName})`
178
+ ].join('\n');
179
+ }
180
+ else {
181
+ instructions = [
182
+ `MCP Server '${normalizedName}' successfully scaffolded at: ${targetDir}`,
183
+ `Kind: Model Context Protocol stdio server`,
184
+ `Security Status: UNGRANTED (Review source files before granting)`,
185
+ '',
186
+ `To register and grant:`,
187
+ ` causyne mcp add ${normalizedName} node ${path.join(targetDir, 'server.js')}`,
188
+ ` causyne mcp grant ${normalizedName}`,
189
+ ` (or in chat: /mcp grant ${normalizedName})`
190
+ ].join('\n');
191
+ }
192
+ const result = {
193
+ success: true,
194
+ route,
195
+ targetDirectory: targetDir,
196
+ createdFiles,
197
+ instructions
198
+ };
199
+ if (digest !== undefined) {
200
+ result.digest = digest;
201
+ }
202
+ return result;
203
+ }
204
+ /**
205
+ * Ensures state.json records the newly scaffolded plugin as disabled.
206
+ */
207
+ recordPluginState(pluginName, digest) {
208
+ try {
209
+ if (!fs.existsSync(this.pluginsRoot)) {
210
+ fs.mkdirSync(this.pluginsRoot, { recursive: true, mode: 0o700 });
211
+ }
212
+ const stateFile = path.join(this.pluginsRoot, 'state.json');
213
+ let state = {
214
+ version: 1,
215
+ plugins: {}
216
+ };
217
+ if (fs.existsSync(stateFile)) {
218
+ try {
219
+ const raw = fs.readFileSync(stateFile, 'utf8');
220
+ const parsed = JSON.parse(raw);
221
+ if (parsed && typeof parsed === 'object') {
222
+ state = { version: 1, plugins: parsed.plugins || {} };
223
+ }
224
+ }
225
+ catch {
226
+ // ignore corrupted state
227
+ }
228
+ }
229
+ state.plugins[pluginName] = {
230
+ enabled: false,
231
+ digest
232
+ };
233
+ const tmp = `${stateFile}.tmp_${process.pid}_${Date.now()}`;
234
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { mode: 0o600 });
235
+ fs.renameSync(tmp, stateFile);
236
+ }
237
+ catch {
238
+ // Graceful fallback if plugins directory is mock or read-only
239
+ }
240
+ }
241
+ }
242
+ /**
243
+ * Top-level convenience function for evaluating route.
244
+ */
245
+ export function assessPluginRoute(service, userPreference) {
246
+ const factory = new PluginsFactory();
247
+ return factory.assess(service, userPreference);
248
+ }
249
+ /**
250
+ * Top-level convenience function for scaffolding.
251
+ */
252
+ export async function scaffoldPlugin(proposal, options) {
253
+ const factory = new PluginsFactory();
254
+ return factory.scaffold(proposal, options);
255
+ }
@@ -0,0 +1,307 @@
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
+ ` (or in chat: /plugins enable ${normalizedName})`
220
+ ].join('\n');
221
+ } else {
222
+ instructions = [
223
+ `MCP Server '${normalizedName}' successfully scaffolded at: ${targetDir}`,
224
+ `Kind: Model Context Protocol stdio server`,
225
+ `Security Status: UNGRANTED (Review source files before granting)`,
226
+ '',
227
+ `To register and grant:`,
228
+ ` causyne mcp add ${normalizedName} node ${path.join(targetDir, 'server.js')}`,
229
+ ` causyne mcp grant ${normalizedName}`,
230
+ ` (or in chat: /mcp grant ${normalizedName})`
231
+ ].join('\n');
232
+ }
233
+
234
+ const result: ScaffoldResult = {
235
+ success: true,
236
+ route,
237
+ targetDirectory: targetDir,
238
+ createdFiles,
239
+ instructions
240
+ };
241
+ if (digest !== undefined) {
242
+ result.digest = digest;
243
+ }
244
+ return result;
245
+ }
246
+
247
+ /**
248
+ * Ensures state.json records the newly scaffolded plugin as disabled.
249
+ */
250
+ private recordPluginState(pluginName: string, digest: string): void {
251
+ try {
252
+ if (!fs.existsSync(this.pluginsRoot)) {
253
+ fs.mkdirSync(this.pluginsRoot, { recursive: true, mode: 0o700 });
254
+ }
255
+ const stateFile = path.join(this.pluginsRoot, 'state.json');
256
+ let state: { version: number; plugins: Record<string, { enabled: boolean; digest?: string }> } = {
257
+ version: 1,
258
+ plugins: {}
259
+ };
260
+
261
+ if (fs.existsSync(stateFile)) {
262
+ try {
263
+ const raw = fs.readFileSync(stateFile, 'utf8');
264
+ const parsed = JSON.parse(raw);
265
+ if (parsed && typeof parsed === 'object') {
266
+ state = { version: 1, plugins: parsed.plugins || {} };
267
+ }
268
+ } catch {
269
+ // ignore corrupted state
270
+ }
271
+ }
272
+
273
+ state.plugins[pluginName] = {
274
+ enabled: false,
275
+ digest
276
+ };
277
+
278
+ const tmp = `${stateFile}.tmp_${process.pid}_${Date.now()}`;
279
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { mode: 0o600 });
280
+ fs.renameSync(tmp, stateFile);
281
+ } catch {
282
+ // Graceful fallback if plugins directory is mock or read-only
283
+ }
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Top-level convenience function for evaluating route.
289
+ */
290
+ export function assessPluginRoute(
291
+ service: ServiceDescriptor,
292
+ userPreference?: RouteKind
293
+ ): FactoryRouteProposal {
294
+ const factory = new PluginsFactory();
295
+ return factory.assess(service, userPreference);
296
+ }
297
+
298
+ /**
299
+ * Top-level convenience function for scaffolding.
300
+ */
301
+ export async function scaffoldPlugin(
302
+ proposal: FactoryRouteProposal,
303
+ options?: ScaffoldOptions
304
+ ): Promise<ScaffoldResult> {
305
+ const factory = new PluginsFactory();
306
+ return factory.scaffold(proposal, options);
307
+ }
@@ -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
+ }