UNPKG

@2501-ai/cli

Version:

[![npm version](https://img.shields.io/npm/v/@2501-ai/cli.svg)](https://www.npmjs.com/package/@2501-ai/cli) [![HumanEval Score](https://img.shields.io/badge/HumanEval-96.95%25-brightgreen.svg)](https://www.2501.ai/research/full-humaneval-benchmark) [![Lic

369 lines (368 loc) 14.1 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_PACKAGE_EXCLUSIONS = exports.WINDOWS_PACKAGE_MANAGERS = exports.MACOS_PACKAGE_MANAGERS = exports.LINUX_PACKAGE_MANAGERS = void 0; exports.getSystemInfo = getSystemInfo; exports.getHostInfo = getHostInfo; const fs_1 = __importDefault(require("fs")); const os_1 = __importDefault(require("os")); const node_util_1 = require("node:util"); const child_process_1 = require("child_process"); const logger_1 = __importDefault(require("./logger")); const execAsync = (0, node_util_1.promisify)(child_process_1.exec); exports.LINUX_PACKAGE_MANAGERS = [ { cmd: 'apt', listCmd: (exclusionPattern) => `apt-mark showmanual 2>/dev/null | grep -vE '${exclusionPattern}'`, }, { cmd: 'dnf', listCmd: (exclusionPattern) => `dnf repoquery --userinstalled --queryformat "%{name}" 2>/dev/null | grep -vE '${exclusionPattern}'`, }, { cmd: 'yum', listCmd: (exclusionPattern) => `yum history userinstalled 2>/dev/null | sed '1d' | xargs -r -- rpm -q --qf '%{NAME}\\n' | grep -vE '${exclusionPattern}'`, }, { cmd: 'pacman', listCmd: (exclusionPattern) => `pacman -Qe | grep -vE '${exclusionPattern}' | awk '{print $1}'`, }, { cmd: 'zypper', listCmd: (exclusionPattern) => `zypper search -i -t package | tail -n +5 | grep -vE '${exclusionPattern}' | awk '{print $3}'`, }, ]; exports.MACOS_PACKAGE_MANAGERS = [ { cmd: 'brew', listCmd: (exclusionPattern) => `brew leaves | grep -vE '${exclusionPattern}'`, }, { cmd: 'port', listCmd: (exclusionPattern) => `port echo requested | grep -vE '${exclusionPattern}' | awk '{print $1}'`, }, ]; exports.WINDOWS_PACKAGE_MANAGERS = [ { cmd: 'winget', listCmd: (exclusionPattern) => `winget list --accept-source-agreements | findstr /v "Name --- ${exclusionPattern}"`, }, { cmd: 'choco', listCmd: (exclusionPattern) => `choco list -lo | findstr /v "Chocolatey packages ${exclusionPattern}"`, }, { cmd: 'scoop', listCmd: (exclusionPattern) => `scoop list | findstr /v "Name --- ${exclusionPattern}"`, }, ]; function getGlobalNpmPackages() { return __awaiter(this, void 0, void 0, function* () { try { const platform = os_1.default.platform(); const command = platform === 'win32' ? 'npm list -g --depth=0 | findstr /R "^[├└]" | findstr "@"' : 'npm list -g --depth=0 | awk "{print $2}" | grep @'; const output = yield execAsync(command, { encoding: 'utf8' }); const packageLines = output.stdout.trim().split('\n').filter(Boolean); if (platform === 'win32') { return packageLines .map((line) => line.replace(/^[+--\s]+/, '').split('@')[0] + '@' + line.split('@')[1]) .filter((pkg) => pkg.includes('@')); } else { return packageLines.filter((pkg) => pkg.includes('@')); } } catch (error) { logger_1.default.debug('Error executing command:', error.message); return []; } }); } function getOSInfo() { return __awaiter(this, void 0, void 0, function* () { try { if (os_1.default.platform() === 'win32') { const { stdout } = yield execAsync('systeminfo'); return stdout.trim(); } else { const { stdout } = yield execAsync('uname -a'); return stdout.trim(); } } catch (error) { logger_1.default.debug('Error getting OS info:', error.message); return (os_1.default.type() + ' ' + os_1.default.release() + ' ' + os_1.default.arch() + ' ' + os_1.default.platform()); } }); } function getPythonVersion() { return __awaiter(this, void 0, void 0, function* () { try { const { stdout } = yield execAsync('python --version'); return stdout.trim(); } catch (_a) { return '(not installed)'; } }); } function getPython3Version() { return __awaiter(this, void 0, void 0, function* () { const { stdout } = yield execAsync('python3 --version'); return stdout.trim(); }); } function getPhpVersion() { return __awaiter(this, void 0, void 0, function* () { try { const { stdout } = yield execAsync('php --version'); return stdout.trim(); } catch (_a) { return '(not installed)'; } }); } function getSystemInfo() { return __awaiter(this, void 0, void 0, function* () { const packageManagers = yield detectPackageManagers(); const installedPackages = yield getInstalledPackages(packageManagers); const osInfo = yield getOSInfo(); const pythonVersion = yield getPython3Version().catch(() => getPythonVersion()); const phpVersion = yield getPhpVersion(); const sysInfo = { platform: os_1.default.platform(), os_info: osInfo, installed_packages: installedPackages, }; return { sysInfo, nodeInfo: { version: process.version, global_packages: yield getGlobalNpmPackages(), }, pythonInfo: { version: pythonVersion, }, phpInfo: { version: phpVersion, }, }; }); } function getPackageManagersForPlatform(exclusionPattern = '') { const platform = os_1.default.platform(); const platformMapping = { linux: exports.LINUX_PACKAGE_MANAGERS, darwin: exports.MACOS_PACKAGE_MANAGERS, win32: exports.WINDOWS_PACKAGE_MANAGERS, }; const packageDefs = platformMapping[platform] || []; return packageDefs.map((pm) => ({ cmd: pm.cmd, listCmd: pm.listCmd(exclusionPattern), })); } exports.DEFAULT_PACKAGE_EXCLUSIONS = [ '^lib', '^python[0-9]?[@]?', '^gcc-', '^perl-', '^php[0-9]?-', '^ruby-', '^tex-', '^fonts-', '^xserver-', '^kernel-', '^linux-', '^openssh-', '^mime-', '^bind[0-9]?-', '^grub-', '^systemd-', '^udev-', '^desktop-', '^glib[0-9]?-', '^gtk[0-9]?-', ]; function detectPackageManagers() { return __awaiter(this, arguments, void 0, function* (options = {}) { const exclusions = [ ...exports.DEFAULT_PACKAGE_EXCLUSIONS, ...(options.additionalExclusions || []), ]; const exclusionPattern = exclusions.join('|'); const packageManagers = getPackageManagersForPlatform(exclusionPattern); const whichCommand = os_1.default.platform() === 'win32' ? 'where' : 'which'; const pmChecks = yield Promise.all(packageManagers.map((pm) => __awaiter(this, void 0, void 0, function* () { try { yield execAsync(`${whichCommand} ${pm.cmd}`); return pm; } catch (error) { logger_1.default.debug(`Failed to find ${pm.cmd}`, { error: error, pm, platform: os_1.default.platform(), }); return null; } }))); return pmChecks.filter(Boolean); }); } function getInstalledPackages(pms) { return __awaiter(this, void 0, void 0, function* () { if (!pms.length) { return {}; } try { const allPackages = yield Promise.all(pms.map((pm) => __awaiter(this, void 0, void 0, function* () { try { const { stdout } = yield execAsync(pm.listCmd); const packages = stdout .split('\n') .filter(Boolean) .sort(); if (packages.length > 0) { return { [`packages installed via ${pm.cmd}`]: packages.join(',') }; } logger_1.default.debug(`No packages found for ${pm.cmd}`); return { [pm.cmd]: '' }; } catch (error) { logger_1.default.error(`Error executing ${pm.cmd}:`, error.message); return { [pm.cmd]: '' }; } }))); return allPackages.reduce((acc, curr) => (Object.assign(Object.assign({}, acc), curr)), {}); } catch (error) { logger_1.default.error('Error getting installed packages:', error.message); return {}; } }); } function commandExists(command) { if (!/^[a-zA-Z0-9\-_]+$/.test(command)) { logger_1.default.error(`Invalid command name: ${command}`); return false; } try { const whichCommand = process.platform === 'win32' ? 'where' : 'which'; (0, child_process_1.execFileSync)(whichCommand, [command], { stdio: ['ignore', 'ignore', 'ignore'], }); return true; } catch (_a) { return false; } } function isValidIPv4(ip) { const parts = ip.split('.'); if (parts.length !== 4) return false; return parts.every((part) => { if (!part || (part.length > 1 && part[0] === '0')) return false; const num = parseInt(part, 10); return !isNaN(num) && num >= 0 && num <= 255 && part === num.toString(); }); } function getPublicIp() { return __awaiter(this, void 0, void 0, function* () { const service = 'https://checkip.amazonaws.com'; try { if (commandExists('curl')) { const { stdout } = yield execAsync('curl -s --max-time 3 ' + service); const result = stdout.trim(); if (result && isValidIPv4(result)) return result; } if (commandExists('wget')) { const { stdout } = yield execAsync('wget -qO- --timeout=3 ' + service); const result = stdout.trim(); if (result && isValidIPv4(result)) return result; } } catch (error) { logger_1.default.error('Failed to fetch public IP:', error.message); } return null; }); } function getHostInfo() { return __awaiter(this, void 0, void 0, function* () { var _a, _b, _c; let unique_id; try { if (process.platform === 'darwin') { unique_id = (0, child_process_1.execSync)("ioreg -d2 -c IOPlatformExpertDevice | awk -F\\\" '/IOPlatformUUID/{print $(NF-1)}'") .toString() .trim(); } else if (process.platform === 'win32') { unique_id = (0, child_process_1.execSync)('reg query "HKLM\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid') .toString() .trim() .split(/\s+/) .pop() || ''; } else { if (fs_1.default.existsSync('/.dockerenv')) { unique_id = process.env.HOSTNAME || os_1.default.hostname(); } else { unique_id = (0, child_process_1.execSync)('cat /var/lib/dbus/machine-id 2>/dev/null || cat /etc/machine-id') .toString() .trim(); } } } catch (_d) { const networkInterfaces = os_1.default.networkInterfaces(); const mac = ((_a = Object.values(networkInterfaces) .flat() .find((iface) => !(iface === null || iface === void 0 ? void 0 : iface.internal) && (iface === null || iface === void 0 ? void 0 : iface.mac))) === null || _a === void 0 ? void 0 : _a.mac) || ''; unique_id = `${os_1.default.hostname()}-${mac}`; } const private_ip = ((_b = Object.values(os_1.default.networkInterfaces()) .flat() .find((iface) => !(iface === null || iface === void 0 ? void 0 : iface.internal) && (iface === null || iface === void 0 ? void 0 : iface.family) === 'IPv4')) === null || _b === void 0 ? void 0 : _b.address) || null; const mac = ((_c = Object.values(os_1.default.networkInterfaces()) .flat() .find((iface) => !(iface === null || iface === void 0 ? void 0 : iface.internal) && (iface === null || iface === void 0 ? void 0 : iface.mac))) === null || _c === void 0 ? void 0 : _c.mac) || null; const public_ip = yield getPublicIp(); const public_ip_note = public_ip ? null : 'Not available: no Internet access or external service unreachable.'; return { unique_id, name: os_1.default.hostname(), private_ip, mac, public_ip, public_ip_note, }; }); }