修复了一些错误 更新了AI.md(给ai看的)
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
"""
|
||||
Node.js Runtime Adapter for NebulaShell
|
||||
=====================================
|
||||
This plugin acts as a pure service provider (Adapter). It does NOT contain its own business logic or pkg.
|
||||
@@ -9,7 +8,6 @@ Usage by other plugins:
|
||||
1. Get this adapter from the shared service registry.
|
||||
2. Call adapter.execute_in_context(plugin_root="./path/to/other-plugin", command="npm start")
|
||||
3. The adapter will automatically switch CWD to "./path/to/other-plugin/pkg" and run the command.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
@@ -19,10 +17,8 @@ import shutil
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
class NodeJSAdapter:
|
||||
"""
|
||||
Pure Node.js Runtime Adapter.
|
||||
Provides execution context switching for other plugins.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.name = "nodejs-adapter"
|
||||
@@ -33,21 +29,6 @@ class NodeJSAdapter:
|
||||
self._detect_runtime()
|
||||
|
||||
def _detect_runtime(self):
|
||||
"""Detect global Node.js and npm installation"""
|
||||
try:
|
||||
self.node_path = shutil.which('node')
|
||||
self.npm_path = shutil.which('npm')
|
||||
|
||||
if not self.node_path:
|
||||
print("[WARNING] Node.js not found in global PATH")
|
||||
if not self.npm_path:
|
||||
print("[WARNING] npm not found in global PATH")
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ERROR] Failed to detect Node.js runtime: {type(e).__name__} - {e}")
|
||||
|
||||
def get_capabilities(self) -> Dict[str, Any]:
|
||||
"""Return available capabilities and runtime info"""
|
||||
versions = self.check_versions()
|
||||
return {
|
||||
'available': bool(self.node_path),
|
||||
@@ -57,23 +38,6 @@ class NodeJSAdapter:
|
||||
}
|
||||
|
||||
def check_versions(self) -> Dict[str, str]:
|
||||
"""Check Node.js and npm versions"""
|
||||
result = {}
|
||||
if self.node_path:
|
||||
try:
|
||||
result['node'] = subprocess.check_output([self.node_path, '--version'], stderr=subprocess.STDOUT).decode().strip()
|
||||
except Exception as e:
|
||||
result['node'] = f"Error: {type(e).__name__} - {e}"
|
||||
|
||||
if self.npm_path:
|
||||
try:
|
||||
result['npm'] = subprocess.check_output([self.npm_path, '--version'], stderr=subprocess.STDOUT).decode().strip()
|
||||
except Exception as e:
|
||||
result['npm'] = f"Error: {type(e).__name__} - {e}"
|
||||
return result
|
||||
|
||||
def execute_in_context(self, plugin_root: str, command_args: List[str], is_npm: bool = False) -> Dict[str, Any]:
|
||||
"""
|
||||
CORE METHOD: Execute a command within the context of another plugin.
|
||||
|
||||
Args:
|
||||
@@ -86,28 +50,22 @@ class NodeJSAdapter:
|
||||
2. Sets cwd to that pkg directory.
|
||||
3. Executes the command.
|
||||
4. Ensures dependencies install into that specific pkg folder.
|
||||
"""
|
||||
if not self.node_path:
|
||||
return {'success': False, 'error': 'Node.js runtime not found'}
|
||||
if is_npm and not self.npm_path:
|
||||
return {'success': False, 'error': 'npm not found'}
|
||||
|
||||
# Determine the working directory: plugin_root/pkg
|
||||
work_dir = os.path.join(plugin_root, 'pkg')
|
||||
|
||||
if not os.path.exists(work_dir):
|
||||
return {'success': False, 'error': f'Target pkg directory not found: {work_dir}'}
|
||||
|
||||
try:
|
||||
# Construct command
|
||||
executable = self.npm_path if is_npm else self.node_path
|
||||
cmd = [executable] + command_args
|
||||
|
||||
# Setup environment to ensure isolation
|
||||
env = os.environ.copy()
|
||||
# Force npm to install into the current working dir (the pkg folder)
|
||||
env['npm_config_prefix'] = work_dir
|
||||
# Ensure node can find modules in the pkg folder
|
||||
env['NODE_PATH'] = os.path.join(work_dir, 'node_modules')
|
||||
|
||||
print(f"[ADAPTER] Executing in context: {work_dir}")
|
||||
@@ -119,8 +77,7 @@ class NodeJSAdapter:
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=300 # 5 min timeout for installs
|
||||
)
|
||||
timeout=300 )
|
||||
|
||||
return {
|
||||
'success': result.returncode == 0,
|
||||
@@ -136,20 +93,16 @@ class NodeJSAdapter:
|
||||
return {'success': False, 'error': f'{type(e).__name__} - {e}'}
|
||||
|
||||
def install_dependencies(self, plugin_root: str, packages: List[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Helper: Install dependencies for a specific plugin.
|
||||
If packages is None, runs 'npm install' (installs from package.json).
|
||||
If packages is provided, runs 'npm install <pkg1> <pkg2>...'.
|
||||
"""
|
||||
args = ['install']
|
||||
if packages:
|
||||
args.extend(packages)
|
||||
return self.execute_in_context(plugin_root, args, is_npm=True)
|
||||
|
||||
def run_script(self, plugin_root: str, script_name: str, extra_args: List[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Helper: Run an npm script (e.g., 'start', 'build') for a specific plugin.
|
||||
"""
|
||||
args = ['run', script_name]
|
||||
if extra_args:
|
||||
args.append('--')
|
||||
@@ -157,25 +110,19 @@ class NodeJSAdapter:
|
||||
return self.execute_in_context(plugin_root, args, is_npm=True)
|
||||
|
||||
def run_file(self, plugin_root: str, file_path: str, args: List[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Helper: Run a specific JS file within a plugin's pkg directory.
|
||||
file_path should be relative to the pkg dir (e.g., 'index.js').
|
||||
"""
|
||||
cmd_args = [file_path]
|
||||
if args:
|
||||
cmd_args.extend(args)
|
||||
return self.execute_in_context(plugin_root, cmd_args, is_npm=False)
|
||||
|
||||
def init_project(self, plugin_root: str, name: str = "plugin-project") -> Dict[str, Any]:
|
||||
"""
|
||||
Helper: Initialize a package.json in the plugin's pkg directory.
|
||||
"""
|
||||
# First run npm init -y
|
||||
res = self.execute_in_context(plugin_root, ['init', '-y'], is_npm=True)
|
||||
if not res['success']:
|
||||
return res
|
||||
|
||||
# Then update the name to be more specific
|
||||
pkg_json_path = os.path.join(plugin_root, 'pkg', 'package.json')
|
||||
if os.path.exists(pkg_json_path):
|
||||
try:
|
||||
@@ -192,14 +139,11 @@ class NodeJSAdapter:
|
||||
return res
|
||||
|
||||
|
||||
# --- Plugin Lifecycle Hooks ---
|
||||
|
||||
def init(context):
|
||||
"""
|
||||
Initialize the adapter and register it as a shared service.
|
||||
This plugin does NOT start any server or run any code itself.
|
||||
It just registers the tool for others to use.
|
||||
"""
|
||||
adapter = NodeJSAdapter()
|
||||
versions = adapter.check_versions()
|
||||
|
||||
@@ -209,7 +153,6 @@ def init(context):
|
||||
if versions.get('npm'):
|
||||
print(f"[INFO] Package Manager: npm {versions['npm']}")
|
||||
|
||||
# Register in shared services so other plugins can retrieve it
|
||||
if 'services' not in context:
|
||||
context['services'] = {}
|
||||
context['services']['nodejs-adapter'] = adapter
|
||||
@@ -222,16 +165,6 @@ def init(context):
|
||||
}
|
||||
|
||||
def start(context):
|
||||
"""No-op: This is a stateless service provider."""
|
||||
return {'status': 'active'}
|
||||
|
||||
def stop(context):
|
||||
"""No-op: Nothing to clean up."""
|
||||
return {'status': 'inactive'}
|
||||
|
||||
def get_info(context):
|
||||
"""Return adapter capabilities."""
|
||||
adapter = context.get('services', {}).get('nodejs-adapter')
|
||||
if adapter:
|
||||
return adapter.get_capabilities()
|
||||
return {'error': 'Adapter service not found'}
|
||||
|
||||
Reference in New Issue
Block a user