@causyne/agent 1.20.112 → 1.20.117

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.
Files changed (169) hide show
  1. package/docs/ARCHITECTURE.md +29 -0
  2. package/package.json +1 -1
  3. package/src/agentLoop.js +153 -68
  4. package/src/agentLoop.ts +152 -71
  5. package/src/browser/browserRuntime.js +13 -8
  6. package/src/browser/browserRuntime.ts +16 -8
  7. package/src/browser/causyneBrowser.js +37 -9
  8. package/src/browser/causyneBrowser.ts +37 -9
  9. package/src/browser/searchProviders.js +18 -7
  10. package/src/browser/searchProviders.ts +17 -5
  11. package/src/browser/snapshotWindow.js +1 -1
  12. package/src/browser/snapshotWindow.ts +1 -1
  13. package/src/browser/urlPolicy.js +21 -10
  14. package/src/browser/urlPolicy.ts +19 -10
  15. package/src/browser/workspacePreview.js +13 -1
  16. package/src/browser/workspacePreview.ts +11 -1
  17. package/src/cliMode.js +5 -1
  18. package/src/computerUse/visionGrounding.js +31 -27
  19. package/src/computerUse/visionGrounding.ts +27 -27
  20. package/src/continuum/ui/continuumPicker.js +14 -6
  21. package/src/continuum/ui/continuumPicker.ts +13 -6
  22. package/src/continuum/ui/continuumPickerView.js +24 -15
  23. package/src/continuum/ui/continuumPickerView.ts +24 -16
  24. package/src/memory/scopedFacts.js +171 -0
  25. package/src/memory/scopedFacts.ts +214 -0
  26. package/src/memory.d.ts +13 -1
  27. package/src/memory.js +9 -12
  28. package/src/observer/advisory.js +32 -22
  29. package/src/observer/advisory.ts +30 -18
  30. package/src/observer/coldObserver.js +21 -33
  31. package/src/observer/coldObserver.ts +20 -33
  32. package/src/observer/evidence.js +20 -13
  33. package/src/observer/evidence.ts +21 -13
  34. package/src/observer.js +47 -12
  35. package/src/observer.ts +50 -18
  36. package/src/perception.js +124 -3
  37. package/src/perception.ts +128 -4
  38. package/src/planCache.js +17 -3
  39. package/src/planCache.ts +17 -3
  40. package/src/pluginsFactory/discovery.js +28 -16
  41. package/src/pluginsFactory/discovery.ts +29 -16
  42. package/src/pluginsFactory/pluginsFactory.js +213 -38
  43. package/src/pluginsFactory/pluginsFactory.ts +218 -39
  44. package/src/pluginsFactory/strategy.js +26 -16
  45. package/src/pluginsFactory/strategy.ts +34 -19
  46. package/src/pluginsFactory/templates.js +183 -62
  47. package/src/pluginsFactory/templates.ts +174 -54
  48. package/src/smartToolsUse.js +4 -5
  49. package/src/smartToolsUse.ts +4 -6
  50. package/src/taskShape.js +49 -7
  51. package/src/taskShape.ts +55 -7
  52. package/src/timeMachine.js +43 -22
  53. package/src/timeMachine.ts +44 -22
  54. package/src/tool-scripts/desktop_act.applescript +1 -0
  55. package/src/toolPacks.js +27 -5
  56. package/src/toolPacks.ts +32 -5
  57. package/src/tools/computerUse.js +23 -10
  58. package/src/tools/computerUse.ts +19 -8
  59. package/src/tools/desktopAct.js +12 -1
  60. package/src/tools/memoryWrite.js +8 -10
  61. package/src/tools/memoryWrite.ts +13 -11
  62. package/src/tools/pluginsFactory.js +108 -5
  63. package/src/tools/pluginsFactory.ts +115 -5
  64. package/src/tui/CausyneRotor.js +24 -10
  65. package/src/tui/CausyneRotor.ts +25 -10
  66. package/src/tui/activityLayout.js +9 -5
  67. package/src/tui/activityLayout.ts +9 -5
  68. package/src/tui/ask.js +34 -14
  69. package/src/tui/banner.js +55 -18
  70. package/src/tui/banner.ts +52 -17
  71. package/src/tui/block.js +47 -20
  72. package/src/tui/block.ts +54 -27
  73. package/src/tui/chatRenderer.js +139 -84
  74. package/src/tui/chatboxClipboard.js +12 -5
  75. package/src/tui/chatboxClipboard.ts +10 -4
  76. package/src/tui/clipboardImage.js +52 -42
  77. package/src/tui/clipboardImage.ts +50 -39
  78. package/src/tui/clipboardSync.js +12 -1
  79. package/src/tui/clipboardSync.ts +9 -1
  80. package/src/tui/codeProgress.js +60 -28
  81. package/src/tui/codeProgress.ts +60 -27
  82. package/src/tui/codeStreamRenderer.js +94 -23
  83. package/src/tui/codeStreamRenderer.ts +92 -23
  84. package/src/tui/commandPresentation.js +9 -2
  85. package/src/tui/commandPresentation.ts +9 -2
  86. package/src/tui/completion.js +45 -23
  87. package/src/tui/composerControls.js +21 -10
  88. package/src/tui/composerControls.ts +18 -10
  89. package/src/tui/composerGeometry.js +6 -4
  90. package/src/tui/composerGeometry.ts +6 -4
  91. package/src/tui/consoleGuard.js +29 -7
  92. package/src/tui/consoleGuard.ts +28 -7
  93. package/src/tui/dialogs.js +134 -71
  94. package/src/tui/diff.js +8 -4
  95. package/src/tui/history.js +6 -5
  96. package/src/tui/home.js +25 -13
  97. package/src/tui/homeView.js +37 -18
  98. package/src/tui/homeView.ts +38 -18
  99. package/src/tui/inlineSlash.js +6 -5
  100. package/src/tui/inlineSlash.ts +6 -5
  101. package/src/tui/keys.js +36 -18
  102. package/src/tui/layout.js +27 -9
  103. package/src/tui/layout.ts +26 -9
  104. package/src/tui/lineEditor.js +49 -23
  105. package/src/tui/markdownMath.js +64 -14
  106. package/src/tui/markdownMath.ts +69 -13
  107. package/src/tui/messageActionPlacement.js +28 -13
  108. package/src/tui/messageActionPlacement.ts +28 -13
  109. package/src/tui/messageInteraction.js +111 -46
  110. package/src/tui/messageInteraction.ts +115 -47
  111. package/src/tui/modelPicker.js +44 -15
  112. package/src/tui/modelPicker.ts +48 -15
  113. package/src/tui/observerPicker.js +56 -13
  114. package/src/tui/observerPicker.ts +73 -30
  115. package/src/tui/overlay.js +79 -35
  116. package/src/tui/overlay.ts +81 -34
  117. package/src/tui/prompt.js +186 -94
  118. package/src/tui/runningLight.js +1 -1
  119. package/src/tui/runningLight.ts +1 -1
  120. package/src/tui/scrollInteraction.js +64 -36
  121. package/src/tui/scrollInteraction.ts +70 -37
  122. package/src/tui/selectList.js +60 -32
  123. package/src/tui/sessionLayout.js +11 -3
  124. package/src/tui/sessionLayout.ts +10 -3
  125. package/src/tui/sessionPicker.js +74 -46
  126. package/src/tui/sessionPicker.ts +73 -48
  127. package/src/tui/sessionPickerView.js +32 -19
  128. package/src/tui/sessionPickerView.ts +31 -18
  129. package/src/tui/sessionSidebar.js +87 -57
  130. package/src/tui/sessionSidebar.ts +90 -54
  131. package/src/tui/setup.js +28 -3
  132. package/src/tui/setup.ts +27 -3
  133. package/src/tui/skillAuthoring.js +11 -5
  134. package/src/tui/skillAuthoring.ts +11 -5
  135. package/src/tui/smartLinkClick.js +75 -23
  136. package/src/tui/smartLinkClick.ts +86 -26
  137. package/src/tui/stage.js +47 -16
  138. package/src/tui/stage.ts +53 -18
  139. package/src/tui/stageSurface.js +232 -51
  140. package/src/tui/statusLine.js +85 -53
  141. package/src/tui/statusLine.ts +82 -46
  142. package/src/tui/terminalInputFramer.js +5 -2
  143. package/src/tui/text.js +117 -46
  144. package/src/tui/text.ts +113 -43
  145. package/src/tui/textLayout.js +6 -4
  146. package/src/tui/textLayout.ts +11 -5
  147. package/src/tui/theme.js +17 -8
  148. package/src/tui/thinkingBox.js +95 -95
  149. package/src/tui/thinkingBox.ts +105 -80
  150. package/src/tui/toolActivityPolicy.js +8 -1
  151. package/src/tui/toolActivityPolicy.ts +7 -1
  152. package/src/tui/toolDisplay.js +15 -6
  153. package/src/tui/toolDisplay.ts +16 -6
  154. package/src/tui/toolOutputNormalizer.js +16 -3
  155. package/src/tui/toolOutputNormalizer.ts +13 -3
  156. package/src/tui/transcript.js +15 -9
  157. package/src/tui/turnRail.js +176 -80
  158. package/src/tui/turnRail.ts +173 -71
  159. package/src/tui/usageCard.js +136 -80
  160. package/src/tui/usageCard.ts +145 -103
  161. package/src/tui/viewport.js +48 -23
  162. package/src/tui/viewport.ts +48 -27
  163. package/src/tui/viewportAnchor.js +2 -2
  164. package/src/tui/viewportAnchor.ts +2 -2
  165. package/src/tui/workspaceFileIndex.js +8 -6
  166. package/src/tui/workspaceFileIndex.ts +8 -6
  167. package/src/tui/workspaceSwitch.js +13 -10
  168. package/src/tui/workspaceSwitch.ts +11 -7
  169. package/src/types/contracts.ts +3 -0
@@ -24,7 +24,8 @@ import {
24
24
  generateCliPluginScaffold,
25
25
  generateHttpPluginScaffold,
26
26
  generateMcpServerScaffold,
27
- generatePythonBridgeScaffold
27
+ generatePythonBridgeScaffold,
28
+ shellQuote
28
29
  } from './templates.js';
29
30
  import type {
30
31
  FactoryRouteProposal,
@@ -32,10 +33,30 @@ import type {
32
33
  RouteKind,
33
34
  ScaffoldOptions,
34
35
  ScaffoldResult,
35
- ServiceDescriptor
36
+ ServiceDescriptor,
37
+ ServiceToolDescriptor
36
38
  } from './types.js';
37
39
 
38
40
  const NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
41
+ const TOOL_NAME_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
42
+ const MAX_TOOLS = 32;
43
+ const CAPABILITIES = new Set(['workspace:read', 'workspace:write', 'network', 'subprocess']);
44
+
45
+ /**
46
+ * Resolves symlinked ancestors even when the final path does not exist yet.
47
+ * Keeps containment checks consistent on macOS, where /var is a symlink.
48
+ */
49
+ function resolveWithExistingAncestors(target: string): string {
50
+ let current = path.resolve(target);
51
+ const missing: string[] = [];
52
+ while (!fs.existsSync(current)) {
53
+ const parent = path.dirname(current);
54
+ if (parent === current) return path.resolve(target);
55
+ missing.unshift(path.basename(current));
56
+ current = parent;
57
+ }
58
+ return path.join(fs.realpathSync(current), ...missing);
59
+ }
39
60
 
40
61
  /**
41
62
  * Computes the exact SHA-256 directory digest matching Causyne's pluginManager.
@@ -124,9 +145,56 @@ export class PluginsFactory {
124
145
  };
125
146
  }
126
147
 
148
+ const normalizedService: ServiceDescriptor = { ...service, name: normalizedName };
127
149
  const route = proposal.userConfirmedRoute ?? proposal.recommendedRoute;
150
+ if (route !== 'native_plugin' && route !== 'python_bridge' && route !== 'mcp_server') {
151
+ return {
152
+ success: false,
153
+ route,
154
+ targetDirectory: '',
155
+ createdFiles: [],
156
+ instructions: '',
157
+ error: `Unsupported route "${String(route)}".`
158
+ };
159
+ }
128
160
  const isMcp = route === 'mcp_server';
129
161
 
162
+ const toolError = this.validateTools(service.tools);
163
+ if (toolError) {
164
+ return {
165
+ success: false,
166
+ route,
167
+ targetDirectory: '',
168
+ createdFiles: [],
169
+ instructions: '',
170
+ error: toolError
171
+ };
172
+ }
173
+
174
+ const capabilityError = this.validateCapabilities(service.capabilities || []);
175
+ if (capabilityError) {
176
+ return {
177
+ success: false,
178
+ route,
179
+ targetDirectory: '',
180
+ createdFiles: [],
181
+ instructions: '',
182
+ error: capabilityError
183
+ };
184
+ }
185
+
186
+ const endpointError = this.validateEndpoint(service, route);
187
+ if (endpointError) {
188
+ return {
189
+ success: false,
190
+ route,
191
+ targetDirectory: '',
192
+ createdFiles: [],
193
+ instructions: '',
194
+ error: endpointError
195
+ };
196
+ }
197
+
130
198
  const baseDir = options.baseDir
131
199
  ? path.resolve(options.baseDir)
132
200
  : isMcp
@@ -135,10 +203,14 @@ export class PluginsFactory {
135
203
 
136
204
  const targetDir = path.join(baseDir, normalizedName);
137
205
 
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)) {
206
+ // Path containment check: resolve the nearest real parent so a symlinked
207
+ // target or parent cannot redirect writes outside the base directory.
208
+ const resolvedBase = resolveWithExistingAncestors(baseDir);
209
+ const targetParent = path.dirname(targetDir);
210
+ const resolvedParent = resolveWithExistingAncestors(targetParent);
211
+ const resolvedTarget = path.join(resolvedParent, path.basename(targetDir));
212
+ const relativeTarget = path.relative(resolvedBase, resolvedTarget);
213
+ if (!relativeTarget || relativeTarget.startsWith('..') || path.isAbsolute(relativeTarget)) {
142
214
  return {
143
215
  success: false,
144
216
  route,
@@ -149,29 +221,52 @@ export class PluginsFactory {
149
221
  };
150
222
  }
151
223
 
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
- };
224
+ if (fs.existsSync(targetDir)) {
225
+ const targetStat = fs.lstatSync(targetDir);
226
+ if (targetStat.isSymbolicLink()) {
227
+ return {
228
+ success: false,
229
+ route,
230
+ targetDirectory: targetDir,
231
+ createdFiles: [],
232
+ instructions: '',
233
+ error: `Target path must not be a symlink: ${targetDir}`
234
+ };
235
+ }
236
+ if (!targetStat.isDirectory()) {
237
+ return {
238
+ success: false,
239
+ route,
240
+ targetDirectory: targetDir,
241
+ createdFiles: [],
242
+ instructions: '',
243
+ error: `Target path is not a directory: ${targetDir}`
244
+ };
245
+ }
246
+ if (!options.force) {
247
+ return {
248
+ success: false,
249
+ route,
250
+ targetDirectory: targetDir,
251
+ createdFiles: [],
252
+ instructions: '',
253
+ error: `Directory already exists: ${targetDir}. Use force: true to overwrite.`
254
+ };
255
+ }
161
256
  }
162
257
 
163
258
  // Select scaffolding payload generator based on route
164
259
  let payload;
165
260
  if (route === 'native_plugin') {
166
261
  if (service.serviceKind === 'cli' || service.cliBinary) {
167
- payload = generateCliPluginScaffold(service);
262
+ payload = generateCliPluginScaffold(normalizedService);
168
263
  } else {
169
- payload = generateHttpPluginScaffold(service);
264
+ payload = generateHttpPluginScaffold(normalizedService);
170
265
  }
171
266
  } else if (route === 'python_bridge') {
172
- payload = generatePythonBridgeScaffold(service);
267
+ payload = generatePythonBridgeScaffold(normalizedService);
173
268
  } else {
174
- payload = generateMcpServerScaffold(service);
269
+ payload = generateMcpServerScaffold(normalizedService);
175
270
  }
176
271
 
177
272
  if (options.dryRun) {
@@ -180,22 +275,56 @@ export class PluginsFactory {
180
275
  route,
181
276
  targetDirectory: targetDir,
182
277
  createdFiles: payload.files.map(f => f.relativePath),
183
- instructions: `[Dry Run] Scaffolding plan ready for ${service.name} at ${targetDir}`
278
+ instructions: `[Dry Run] Scaffolding plan ready for ${normalizedName} at ${targetDir}`
184
279
  };
185
280
  }
186
281
 
187
282
  // Write files to target directory
188
- fs.mkdirSync(targetDir, { recursive: true, mode: 0o700 });
283
+ const createdRoot = !fs.existsSync(targetDir);
189
284
  const createdFiles: string[] = [];
190
285
 
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 });
286
+ try {
287
+ fs.mkdirSync(targetDir, { recursive: true, mode: 0o700 });
288
+ for (const file of payload.files) {
289
+ const filePath = path.join(targetDir, file.relativePath);
290
+ const fileDir = path.dirname(filePath);
291
+ if (fs.existsSync(fileDir)) {
292
+ const dirStat = fs.lstatSync(fileDir);
293
+ if (dirStat.isSymbolicLink()) {
294
+ throw new Error(`Refusing to write through symlinked directory: ${fileDir}`);
295
+ }
296
+ }
297
+ if (fs.existsSync(filePath)) {
298
+ const fileStat = fs.lstatSync(filePath);
299
+ if (fileStat.isSymbolicLink()) {
300
+ throw new Error(`Refusing to overwrite symlinked file: ${filePath}`);
301
+ }
302
+ if (!fileStat.isFile()) {
303
+ throw new Error(`Refusing to overwrite non-file path: ${filePath}`);
304
+ }
305
+ }
306
+ if (!fs.existsSync(fileDir)) {
307
+ fs.mkdirSync(fileDir, { recursive: true, mode: 0o700 });
308
+ }
309
+ fs.writeFileSync(filePath, file.content, { encoding: 'utf8', mode: 0o600 });
310
+ createdFiles.push(file.relativePath);
311
+ }
312
+ } catch (err) {
313
+ if (createdRoot) {
314
+ try {
315
+ fs.rmSync(targetDir, { recursive: true, force: true });
316
+ } catch {
317
+ // Preserve the original write failure.
318
+ }
196
319
  }
197
- fs.writeFileSync(filePath, file.content, { encoding: 'utf8', mode: 0o600 });
198
- createdFiles.push(file.relativePath);
320
+ return {
321
+ success: false,
322
+ route,
323
+ targetDirectory: targetDir,
324
+ createdFiles: [],
325
+ instructions: '',
326
+ error: `Failed to scaffold ${normalizedName}: ${err instanceof Error ? err.message : String(err)}`
327
+ };
199
328
  }
200
329
 
201
330
  let digest: string | undefined;
@@ -205,8 +334,8 @@ export class PluginsFactory {
205
334
  // Calculate plugin digest
206
335
  digest = computePluginDirectoryDigest(targetDir);
207
336
 
208
- // Record disabled state in state.json
209
- this.recordPluginState(normalizedName, digest);
337
+ // Record disabled state in state.json next to the scaffolded plugin.
338
+ this.recordPluginState(normalizedName, digest, baseDir);
210
339
 
211
340
  instructions = [
212
341
  `Custom plugin '${normalizedName}' successfully scaffolded at: ${targetDir}`,
@@ -215,8 +344,7 @@ export class PluginsFactory {
215
344
  `Security Status: DISABLED (Review source files before enabling)`,
216
345
  '',
217
346
  `To activate after review:`,
218
- ` causyne plugins enable ${normalizedName}`,
219
- ` (or in chat: /plugins enable ${normalizedName})`
347
+ ` /plugins enable ${normalizedName}`
220
348
  ].join('\n');
221
349
  } else {
222
350
  instructions = [
@@ -225,7 +353,7 @@ export class PluginsFactory {
225
353
  `Security Status: UNGRANTED (Review source files before granting)`,
226
354
  '',
227
355
  `To register and grant:`,
228
- ` causyne mcp add ${normalizedName} node ${path.join(targetDir, 'server.js')}`,
356
+ ` causyne mcp add ${normalizedName} node ${shellQuote(path.join(targetDir, 'server.js'))}`,
229
357
  ` causyne mcp grant ${normalizedName}`,
230
358
  ` (or in chat: /mcp grant ${normalizedName})`
231
359
  ].join('\n');
@@ -244,15 +372,63 @@ export class PluginsFactory {
244
372
  return result;
245
373
  }
246
374
 
375
+ /**
376
+ * Rejects descriptors that the plugin loader would refuse after the factory
377
+ * has already written files and recorded a digest.
378
+ */
379
+ private validateTools(tools: ServiceToolDescriptor[]): string | null {
380
+ if (tools.length > MAX_TOOLS) {
381
+ return `Plugin exceeds ${MAX_TOOLS} tools.`;
382
+ }
383
+ const seen = new Set<string>();
384
+ for (const tool of tools) {
385
+ if (!TOOL_NAME_PATTERN.test(tool.name)) {
386
+ return `Invalid tool name "${tool.name}". Must match ^[a-z][a-z0-9_-]{0,63}$`;
387
+ }
388
+ if (seen.has(tool.name)) {
389
+ return `Duplicate tool name "${tool.name}".`;
390
+ }
391
+ seen.add(tool.name);
392
+ if (!tool.parameters || tool.parameters.type !== 'object') {
393
+ return `Tool "${tool.name}" parameters must be an object JSON schema.`;
394
+ }
395
+ }
396
+ return null;
397
+ }
398
+
399
+ private validateCapabilities(capabilities: string[]): string | null {
400
+ for (const capability of capabilities) {
401
+ if (!CAPABILITIES.has(capability)) {
402
+ return `Unknown capability "${capability}".`;
403
+ }
404
+ }
405
+ return null;
406
+ }
407
+
408
+ private validateEndpoint(service: ServiceDescriptor, route: RouteKind): string | null {
409
+ const isHttpNative = route === 'native_plugin' && service.serviceKind !== 'cli' && !service.cliBinary;
410
+ if (!isHttpNative || !service.endpoint) return null;
411
+ let parsed: URL;
412
+ try {
413
+ parsed = new URL(service.endpoint);
414
+ } catch {
415
+ return `Invalid endpoint URL "${service.endpoint}".`;
416
+ }
417
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
418
+ return `Endpoint must use http or https, received "${parsed.protocol}".`;
419
+ }
420
+ return null;
421
+ }
422
+
247
423
  /**
248
424
  * Ensures state.json records the newly scaffolded plugin as disabled.
249
425
  */
250
- private recordPluginState(pluginName: string, digest: string): void {
426
+ private recordPluginState(pluginName: string, digest: string, stateRoot: string = this.pluginsRoot): void {
251
427
  try {
252
- if (!fs.existsSync(this.pluginsRoot)) {
253
- fs.mkdirSync(this.pluginsRoot, { recursive: true, mode: 0o700 });
428
+ if (!fs.existsSync(stateRoot)) {
429
+ fs.mkdirSync(stateRoot, { recursive: true, mode: 0o700 });
254
430
  }
255
- const stateFile = path.join(this.pluginsRoot, 'state.json');
431
+ const stateFile = path.join(stateRoot, 'state.json');
256
432
  let state: { version: number; plugins: Record<string, { enabled: boolean; digest?: string }> } = {
257
433
  version: 1,
258
434
  plugins: {}
@@ -262,8 +438,11 @@ export class PluginsFactory {
262
438
  try {
263
439
  const raw = fs.readFileSync(stateFile, 'utf8');
264
440
  const parsed = JSON.parse(raw);
265
- if (parsed && typeof parsed === 'object') {
266
- state = { version: 1, plugins: parsed.plugins || {} };
441
+ const parsedPlugins = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
442
+ ? parsed.plugins
443
+ : undefined;
444
+ if (parsedPlugins && typeof parsedPlugins === 'object' && !Array.isArray(parsedPlugins)) {
445
+ state = { version: 1, plugins: parsedPlugins };
267
446
  }
268
447
  } catch {
269
448
  // ignore corrupted state
@@ -37,17 +37,25 @@ function isPythonSpecific(service) {
37
37
  const descLower = (service.description || '').toLowerCase();
38
38
  return PYTHON_KEYWORDS.some(kw => nameLower.includes(kw) || descLower.includes(kw));
39
39
  }
40
+ const ROUTE_KINDS = ['native_plugin', 'python_bridge', 'mcp_server'];
40
41
  export function assessRoute(service, userPreference) {
41
42
  const costComparison = estimateServiceCosts(service);
42
- const existingCapability = findExistingCapability(service.name);
43
- // 1. User Preference Override
44
- const chosenRoute = userPreference ?? service.userPreferredRoute;
43
+ const capabilityQuery = [service.name, ...service.tools.map(tool => tool.name)].join(' ');
44
+ const existingCapability = findExistingCapability(capabilityQuery);
45
+ const reasonWithCapability = (reason) => {
46
+ if (!existingCapability.covered)
47
+ return reason;
48
+ return `${reason} Existing capability detected: ${existingCapability.details}. Reuse it unless this integration adds distinct behavior.`;
49
+ };
50
+ // 1. User Preference Override (invalid runtime values fall back to heuristics)
51
+ const requestedRoute = userPreference ?? service.userPreferredRoute;
52
+ const chosenRoute = requestedRoute && ROUTE_KINDS.includes(requestedRoute) ? requestedRoute : undefined;
45
53
  if (chosenRoute) {
46
54
  const isMcp = chosenRoute === 'mcp_server';
47
55
  const proposal = {
48
56
  service,
49
57
  recommendedRoute: chosenRoute,
50
- reason: `Honoring user explicit preference for route '${chosenRoute}'.`,
58
+ reason: reasonWithCapability(`Honoring user explicit preference for route '${chosenRoute}'.`),
51
59
  costComparison,
52
60
  userConsentRequired: false,
53
61
  userConfirmedRoute: chosenRoute,
@@ -58,26 +66,28 @@ export function assessRoute(service, userPreference) {
58
66
  }
59
67
  return proposal;
60
68
  }
61
- // 2. Python SDK Route (Bridge Buffer)
62
- if (isPythonSpecific(service)) {
69
+ // 2. MCP-Only Service Route (explicit kind wins over keyword heuristics)
70
+ if (service.serviceKind === 'mcp_only') {
63
71
  return {
64
72
  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.',
73
+ recommendedRoute: 'mcp_server',
74
+ reason: reasonWithCapability('Service exclusively exposes an MCP endpoint or protocol. Recommending MCP server scaffold with token overhead disclosure.'),
67
75
  costComparison,
68
- userConsentRequired: false,
76
+ mcpDisclosure: formatMcpDisclosure(service.name, costComparison),
77
+ userConsentRequired: true,
69
78
  existingCapability: existingCapability.covered ? existingCapability : undefined
70
79
  };
71
80
  }
72
- // 3. MCP-Only Service Route
73
- if (service.serviceKind === 'mcp_only') {
81
+ // 3. Python SDK Route (Bridge Buffer). HTTP and CLI services keep their
82
+ // declared transport even if their description mentions Python.
83
+ if (service.serviceKind === 'python_sdk' ||
84
+ (service.serviceKind === 'custom' && isPythonSpecific(service))) {
74
85
  return {
75
86
  service,
76
- recommendedRoute: 'mcp_server',
77
- reason: 'Service exclusively exposes an MCP endpoint or protocol. Recommending MCP server scaffold with token overhead disclosure.',
87
+ recommendedRoute: 'python_bridge',
88
+ reason: reasonWithCapability('Service depends on Python SDK or specialized scientific/creative modules. A Python bridge provides an on-demand subprocess buffer without full MCP overhead.'),
78
89
  costComparison,
79
- mcpDisclosure: formatMcpDisclosure(service.name, costComparison),
80
- userConsentRequired: true,
90
+ userConsentRequired: false,
81
91
  existingCapability: existingCapability.covered ? existingCapability : undefined
82
92
  };
83
93
  }
@@ -85,7 +95,7 @@ export function assessRoute(service, userPreference) {
85
95
  return {
86
96
  service,
87
97
  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.',
98
+ reason: reasonWithCapability('Service supports HTTP/REST API or CLI interface. Native plugin is selected as the most token-lean and cost-effective route.'),
89
99
  costComparison,
90
100
  userConsentRequired: false,
91
101
  existingCapability: existingCapability.covered ? existingCapability : undefined
@@ -40,21 +40,29 @@ function isPythonSpecific(service: ServiceDescriptor): boolean {
40
40
  return PYTHON_KEYWORDS.some(kw => nameLower.includes(kw) || descLower.includes(kw));
41
41
  }
42
42
 
43
+ const ROUTE_KINDS: RouteKind[] = ['native_plugin', 'python_bridge', 'mcp_server'];
44
+
43
45
  export function assessRoute(
44
46
  service: ServiceDescriptor,
45
47
  userPreference?: RouteKind
46
48
  ): FactoryRouteProposal {
47
49
  const costComparison = estimateServiceCosts(service);
48
- const existingCapability = findExistingCapability(service.name);
50
+ const capabilityQuery = [service.name, ...service.tools.map(tool => tool.name)].join(' ');
51
+ const existingCapability = findExistingCapability(capabilityQuery);
52
+ const reasonWithCapability = (reason: string): string => {
53
+ if (!existingCapability.covered) return reason;
54
+ return `${reason} Existing capability detected: ${existingCapability.details}. Reuse it unless this integration adds distinct behavior.`;
55
+ };
49
56
 
50
- // 1. User Preference Override
51
- const chosenRoute = userPreference ?? service.userPreferredRoute;
57
+ // 1. User Preference Override (invalid runtime values fall back to heuristics)
58
+ const requestedRoute = userPreference ?? service.userPreferredRoute;
59
+ const chosenRoute = requestedRoute && ROUTE_KINDS.includes(requestedRoute) ? requestedRoute : undefined;
52
60
  if (chosenRoute) {
53
61
  const isMcp = chosenRoute === 'mcp_server';
54
62
  const proposal: FactoryRouteProposal = {
55
63
  service,
56
64
  recommendedRoute: chosenRoute,
57
- reason: `Honoring user explicit preference for route '${chosenRoute}'.`,
65
+ reason: reasonWithCapability(`Honoring user explicit preference for route '${chosenRoute}'.`),
58
66
  costComparison,
59
67
  userConsentRequired: false,
60
68
  userConfirmedRoute: chosenRoute,
@@ -66,29 +74,35 @@ export function assessRoute(
66
74
  return proposal;
67
75
  }
68
76
 
69
- // 2. Python SDK Route (Bridge Buffer)
70
- if (isPythonSpecific(service)) {
77
+ // 2. MCP-Only Service Route (explicit kind wins over keyword heuristics)
78
+ if (service.serviceKind === 'mcp_only') {
71
79
  return {
72
80
  service,
73
- recommendedRoute: 'python_bridge',
74
- reason:
75
- 'Service depends on Python SDK or specialized scientific/creative modules. A Python bridge provides an on-demand subprocess buffer without full MCP overhead.',
81
+ recommendedRoute: 'mcp_server',
82
+ reason: reasonWithCapability(
83
+ 'Service exclusively exposes an MCP endpoint or protocol. Recommending MCP server scaffold with token overhead disclosure.'
84
+ ),
76
85
  costComparison,
77
- userConsentRequired: false,
86
+ mcpDisclosure: formatMcpDisclosure(service.name, costComparison),
87
+ userConsentRequired: true,
78
88
  existingCapability: existingCapability.covered ? existingCapability : undefined
79
89
  };
80
90
  }
81
91
 
82
- // 3. MCP-Only Service Route
83
- if (service.serviceKind === 'mcp_only') {
92
+ // 3. Python SDK Route (Bridge Buffer). HTTP and CLI services keep their
93
+ // declared transport even if their description mentions Python.
94
+ if (
95
+ service.serviceKind === 'python_sdk' ||
96
+ (service.serviceKind === 'custom' && isPythonSpecific(service))
97
+ ) {
84
98
  return {
85
99
  service,
86
- recommendedRoute: 'mcp_server',
87
- reason:
88
- 'Service exclusively exposes an MCP endpoint or protocol. Recommending MCP server scaffold with token overhead disclosure.',
100
+ recommendedRoute: 'python_bridge',
101
+ reason: reasonWithCapability(
102
+ 'Service depends on Python SDK or specialized scientific/creative modules. A Python bridge provides an on-demand subprocess buffer without full MCP overhead.'
103
+ ),
89
104
  costComparison,
90
- mcpDisclosure: formatMcpDisclosure(service.name, costComparison),
91
- userConsentRequired: true,
105
+ userConsentRequired: false,
92
106
  existingCapability: existingCapability.covered ? existingCapability : undefined
93
107
  };
94
108
  }
@@ -97,8 +111,9 @@ export function assessRoute(
97
111
  return {
98
112
  service,
99
113
  recommendedRoute: 'native_plugin',
100
- reason:
101
- 'Service supports HTTP/REST API or CLI interface. Native plugin is selected as the most token-lean and cost-effective route.',
114
+ reason: reasonWithCapability(
115
+ 'Service supports HTTP/REST API or CLI interface. Native plugin is selected as the most token-lean and cost-effective route.'
116
+ ),
102
117
  costComparison,
103
118
  userConsentRequired: false,
104
119
  existingCapability: existingCapability.covered ? existingCapability : undefined