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.
| Parameter | Type | Required | Description |
|---|---|---|---|
| packageManager | String | Yes | Package manager to use: 'pip', 'npm', or 'apt' |
| packages | Array | Yes | List of packages to install |
| requirements | String | No | Requirements file content (for pip/npm) |
| version | String | No | Specific version constraint |
| options | Object | No | Installation options |
| options.upgrade | Boolean | No | Upgrade existing packages |
| options.userInstall | Boolean | No | Install in user directory (pip only) |
| options.devDependencies | Boolean | No | Include dev dependencies (npm only) |
| options.force | Boolean | No | Force installation (use with caution) |
{
"packageManager": "pip",
"packages": ["pandas", "numpy>=1.21.0"],
"options": {
"userInstall": true,
"upgrade": false
}
}Output:
success(Boolean) - Installation success statusinstalledPackages(Array) - List of successfully installed packagesname(String) - Package nameversion(String) - Installed versionsize(Number) - Installation size in bytesdependencies(Array) - List of installed dependencies
errors(Array) - Installation error messageswarnings(Array) - Security warning messagessecurityScan(Object) - Security analysis resultsvulnerabilities(Array) - Found security vulnerabilitiesreputation(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
- Version Pinning - Use specific versions for production dependencies
- Security Scanning - Review security scan results before installation
- Dependency Review - Audit all installed dependencies
- Regular Updates - Keep packages updated for security patches
Installation Safety
- Size Monitoring - Monitor installation sizes and disk usage
- Timeout Management - Set appropriate installation timeouts
- Error Handling - Implement comprehensive error handling
- Rollback Plans - Prepare rollback strategies for failed installations
Environment Isolation
- User Installation - Use user-level installation when possible
- Virtual Environments - Isolate project dependencies
- Minimal Installation - Install only required packages
- Resource Limits - Respect sandbox resource constraints
Error Handling and Troubleshooting
Common Installation Issues
| Error Type | Symptoms | Resolution |
|---|---|---|
| Package Not Found | Package name not found in repository | Verify package name and repository |
| Version Conflict | Dependency version conflicts | Use compatible versions or constraints |
| Size Limit Exceeded | Installation exceeds size limits | Remove unnecessary packages or request more space |
| Network Timeout | Download timeout during installation | Retry installation or check connectivity |
| Permission Denied | Insufficient installation permissions | Use 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()Related Tools
Code Execution
Execute code with dynamically installed packages and dependencies
Command Execution
Use installed system packages and command-line tools
File System Tools
Upload requirements files and manage package installation artifacts
Next Steps: Start with Code Execution to use installed packages, or explore File System Tools for dependency file management.