logo_smallAxellero.io

Package Installer

Install and manage Python, Node.js, and system packages safely within isolated sandbox environments.

Package Installer

Securely install and manage Python, Node.js, and system packages within isolated sandbox environments with comprehensive security validation and dependency management.

📦 Secure Package Management

Package installation includes security scanning, vulnerability checking, and size limitations to ensure safe dependency management within the sandbox environment.

Overview

The Package Installer tool provides secure package management capabilities for Python (pip), Node.js (npm), and system packages (apt) with comprehensive security controls, dependency validation, and installation monitoring.

Key Features

  • Multi-Platform Support - Python pip, Node.js npm, and system apt packages
  • Security Scanning - Vulnerability detection and package reputation checking
  • Dependency Resolution - Automatic dependency management and conflict resolution
  • Size Limitations - Installation size limits and download restrictions
  • Version Control - Specific version installation and constraint management

Methods

packageInstaller

Install packages securely within the sandbox environment.

ParameterTypeRequiredDescription
packageManagerStringYesPackage manager to use: 'pip', 'npm', or 'apt'
packagesArrayYesList of packages to install
requirementsStringNoRequirements file content (for pip/npm)
versionStringNoSpecific version constraint
optionsObjectNoInstallation options
options.upgradeBooleanNoUpgrade existing packages
options.userInstallBooleanNoInstall in user directory (pip only)
options.devDependenciesBooleanNoInclude dev dependencies (npm only)
options.forceBooleanNoForce installation (use with caution)
{
  "packageManager": "pip",
  "packages": ["pandas", "numpy>=1.21.0"],
  "options": {
    "userInstall": true,
    "upgrade": false
  }
}

Output:

  • success (Boolean) - Installation success status
  • installedPackages (Array) - List of successfully installed packages
    • name (String) - Package name
    • version (String) - Installed version
    • size (Number) - Installation size in bytes
    • dependencies (Array) - List of installed dependencies
  • errors (Array) - Installation error messages
  • warnings (Array) - Security warning messages
  • securityScan (Object) - Security analysis results
    • vulnerabilities (Array) - Found security vulnerabilities
    • reputation (Array) - Package reputation scores
  • installationTime (Number) - Installation duration in seconds

Python Package Management (pip)

Supported Features

Node.js Package Management (npm)

Supported Features

System Package Management (apt)

Supported Features

⚠️ Restricted System Packages

System package installation is heavily restricted to essential development and utility packages only. Security scanning is mandatory for all system packages.

Installation Workflows

Multi-Language Environment Setup

# Complete development environment setup
import subprocess
import json

def setup_development_environment():
    """Set up a complete development environment."""
    
    # 1. Install system dependencies
    system_packages = [
        "build-essential", "git", "curl", "wget", "unzip", "jq", "tree"
    ]
    
    system_result = packageInstaller({
        "packageManager": "apt",
        "packages": system_packages
    })
    
    # 2. Install Python packages for data science
    python_requirements = """
pandas>=1.4.0
numpy>=1.21.0
matplotlib>=3.5.0
seaborn>=0.11.0
scikit-learn>=1.1.0
jupyter>=1.0.0
requests>=2.27.0
beautifulsoup4>=4.11.0
openpyxl>=3.0.0
    """.strip()
    
    python_result = packageInstaller({
        "packageManager": "pip",
        "packages": [],
        "requirements": python_requirements,
        "options": {"userInstall": True}
    })
    
    # 3. Install Node.js packages for web development
    npm_packages = [
        "express@^4.18.0",
        "axios@^1.3.0", 
        "lodash@^4.17.21",
        "moment@^2.29.0",
        "csv-parser@^3.0.0"
    ]
    
    npm_result = packageInstaller({
        "packageManager": "npm",
        "packages": npm_packages
    })
    
    # Return setup summary
    return {
        "system": system_result,
        "python": python_result,
        "nodejs": npm_result
    }

# Execute setup
setup_result = setup_development_environment()
print("Environment setup completed!")

Project-Specific Installation

def install_project_dependencies(project_type):
    """Install dependencies based on project type."""
    
    if project_type == "data-science":
        return packageInstaller({
            "packageManager": "pip",
            "packages": [
                "pandas", "numpy", "matplotlib", "seaborn",
                "scikit-learn", "scipy", "jupyter"
            ]
        })
    
    elif project_type == "web-scraping":
        return packageInstaller({
            "packageManager": "pip", 
            "packages": [
                "requests", "beautifulsoup4", "selenium",
                "scrapy", "lxml", "pandas"
            ]
        })
    
    elif project_type == "api-development":
        return packageInstaller({
            "packageManager": "npm",
            "packages": [
                "express", "axios", "cors", "helmet",
                "joi", "bcrypt", "jsonwebtoken"
            ]
        })
    
    elif project_type == "data-processing":
        # Multi-language setup
        pip_result = packageInstaller({
            "packageManager": "pip",
            "packages": ["pandas", "openpyxl", "python-docx"]
        })
        
        npm_result = packageInstaller({
            "packageManager": "npm", 
            "packages": ["csv-parser", "json2csv", "papaparse"]
        })
        
        return {"python": pip_result, "nodejs": npm_result}

# Install based on project needs
dependencies = install_project_dependencies("data-science")

Security Best Practices

🔒 Security Guidelines

Package Validation

  1. Version Pinning - Use specific versions for production dependencies
  2. Security Scanning - Review security scan results before installation
  3. Dependency Review - Audit all installed dependencies
  4. Regular Updates - Keep packages updated for security patches

Installation Safety

  1. Size Monitoring - Monitor installation sizes and disk usage
  2. Timeout Management - Set appropriate installation timeouts
  3. Error Handling - Implement comprehensive error handling
  4. Rollback Plans - Prepare rollback strategies for failed installations

Environment Isolation

  1. User Installation - Use user-level installation when possible
  2. Virtual Environments - Isolate project dependencies
  3. Minimal Installation - Install only required packages
  4. Resource Limits - Respect sandbox resource constraints

Error Handling and Troubleshooting

Common Installation Issues

Error TypeSymptomsResolution
Package Not FoundPackage name not found in repositoryVerify package name and repository
Version ConflictDependency version conflictsUse compatible versions or constraints
Size Limit ExceededInstallation exceeds size limitsRemove unnecessary packages or request more space
Network TimeoutDownload timeout during installationRetry installation or check connectivity
Permission DeniedInsufficient installation permissionsUse user installation or check permissions

Installation Monitoring

def monitor_installation_progress(package_manager, packages):
    """Monitor package installation with progress tracking."""
    
    import time
    start_time = time.time()
    
    try:
        result = packageInstaller({
            "packageManager": package_manager,
            "packages": packages
        })
        
        end_time = time.time()
        installation_duration = end_time - start_time
        
        # Log installation details
        print(f"Installation completed in {installation_duration:.2f} seconds")
        print(f"Packages installed: {len(result['installedPackages'])}")
        
        # Check for security issues
        if result['securityScan']['vulnerabilities']:
            print("⚠️ Security vulnerabilities found:")
            for vuln in result['securityScan']['vulnerabilities']:
                print(f"  - {vuln['package']}: {vuln['severity']} - {vuln['description']}")
        
        # Display warnings
        if result['warnings']:
            print("📝 Installation warnings:")
            for warning in result['warnings']:
                print(f"  - {warning}")
        
        return result
        
    except Exception as e:
        print(f"❌ Installation failed: {str(e)}")
        return None

# Usage example
result = monitor_installation_progress("pip", ["pandas", "numpy", "matplotlib"])

Dependency Management

def manage_package_dependencies():
    """Advanced dependency management with conflict resolution."""
    
    # Check current installed packages
    pip_list = subprocess.run(['pip', 'list', '--format=json'], 
                             capture_output=True, text=True)
    current_packages = json.loads(pip_list.stdout)
    
    # Install new packages with dependency checking
    new_packages = ["tensorflow", "torch", "transformers"]
    
    for package in new_packages:
        try:
            # Check if package conflicts with existing packages
            result = packageInstaller({
                "packageManager": "pip",
                "packages": [package],
                "options": {"upgrade": False}
            })
            
            if result['success']:
                print(f"✅ {package} installed successfully")
            else:
                print(f"❌ {package} installation failed: {result['errors']}")
                
        except Exception as e:
            print(f"⚠️ Error installing {package}: {str(e)}")
    
    return True

# Execute dependency management
manage_package_dependencies()

Integration Patterns

With Code Execution Tools

# Install packages at runtime based on code requirements
def dynamic_package_installation(code_content):
    """Analyze code and install required packages dynamically."""
    
    import re
    
    # Extract import statements
    import_pattern = r'^(?:from|import)\s+([^\s\.\;]+)'
    imports = re.findall(import_pattern, code_content, re.MULTILINE)
    
    # Map common imports to package names
    package_mapping = {
        'pandas': 'pandas',
        'numpy': 'numpy', 
        'matplotlib': 'matplotlib',
        'requests': 'requests',
        'bs4': 'beautifulsoup4',
        'sklearn': 'scikit-learn'
    }
    
    required_packages = []
    for imp in imports:
        if imp in package_mapping:
            required_packages.append(package_mapping[imp])
    
    # Install required packages
    if required_packages:
        result = packageInstaller({
            "packageManager": "pip",
            "packages": required_packages,
            "options": {"userInstall": True}
        })
        return result
    
    return None

# Example usage
code = """
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
"""

# Install packages before code execution
dynamic_package_installation(code)

With File System Tools

# Install packages from uploaded requirements files
def install_from_uploaded_requirements():
    """Install packages from uploaded requirements files."""
    
    # Read requirements from uploaded file
    with open('/sandbox/uploads/requirements.txt', 'r') as f:
        requirements_content = f.read()
    
    # Install Python packages
    pip_result = packageInstaller({
        "packageManager": "pip",
        "packages": [],
        "requirements": requirements_content
    })
    
    # Check for package.json
    try:
        with open('/sandbox/uploads/package.json', 'r') as f:
            package_json = f.read()
        
        # Install Node.js packages
        npm_result = packageInstaller({
            "packageManager": "npm",
            "packages": [],
            "requirements": package_json
        })
        
        return {"pip": pip_result, "npm": npm_result}
        
    except FileNotFoundError:
        return {"pip": pip_result}

# Execute installation from uploaded files
installation_result = install_from_uploaded_requirements()

Next Steps: Start with Code Execution to use installed packages, or explore File System Tools for dependency file management.