UNPKG

@notbeastr/powerai

Version:

PowerAI - Advanced Windows PowerShell AI Assistant with Agentic Coding (T Mode), Multi-language Script Execution, and RAG System

1,443 lines (1,204 loc) 72.2 kB
#!/usr/bin/env node import fs from "fs-extra"; import readlineSync from "readline-sync"; import { GoogleGenerativeAI } from "@google/generative-ai"; import chalk from "chalk"; import ora from "ora"; import path from "path"; import fetch from "node-fetch"; import { exec } from "child_process"; import { fileURLToPath } from "url"; import os from "os"; import { promisify } from "util"; import boxen from "boxen"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); // Windows-specific paths const CONFIG_DIR = path.join(process.env.APPDATA || os.homedir(), '.powerai'); const CONFIG_PATH = path.join(CONFIG_DIR, 'config.json'); const KNOWLEDGE_PATH = path.join(CONFIG_DIR, 'knowledge.json'); const PSREMOTE_CONFIG_PATH = path.join(CONFIG_DIR, 'psremote_config.json'); const execAsync = promisify(exec); // Check if running on Windows (desktop only, not Server) if (os.platform() !== 'win32') { console.error(chalk.red('❌ ERROR: PowerAI requires Windows operating system.')); console.error(chalk.yellow('This tool is specifically designed for Windows PowerShell.')); process.exit(1); } // Block Windows Server editions try { const { stdout } = await execAsync('powershell.exe -NoProfile -Command "(Get-WmiObject -Class Win32_OperatingSystem).Caption"', { encoding: 'utf8' }); if (stdout.toLowerCase().includes('server')) { console.error(chalk.red('❌ ERROR: PowerAI is designed for Windows Desktop editions only.')); console.error(chalk.yellow('Windows Server is not supported. Please use Windows 10 or Windows 11.')); process.exit(1); } } catch (error) { // If we can't check, allow it to proceed } // -------------------- THEME SYSTEM -------------------- class ThemeManager { static getTheme() { return { primary: chalk.magentaBright, secondary: chalk.cyan, accent: chalk.yellow, success: chalk.green, warning: chalk.yellow, error: chalk.red, info: chalk.blue, muted: chalk.gray, bg: chalk.bgMagenta, highlight: chalk.bold.cyan }; } } // -------------------- INTERFACE COMPONENTS -------------------- class Interface { static getTheme() { return ThemeManager.getTheme(); } static printHeader(title, subtitle = "") { const theme = this.getTheme(); const headerBox = boxen( `${theme.primary.bold(title)}\n${theme.muted(subtitle)}`, { padding: 1, margin: 1, borderStyle: 'round', borderColor: 'magenta', backgroundColor: 'black' } ); console.log(headerBox); } static printSection(title, content) { const theme = this.getTheme(); console.log(`\n${theme.accent(`╭─ ${title} ─`)}`); console.log(`${theme.info(`│ ${content}`)}`); console.log(`${theme.accent(`╰${'─'.repeat(title.length + 4)}`)}\n`); } static printCommand(cmd, description) { const theme = this.getTheme(); console.log( ` ${theme.secondary('•')} ${theme.highlight(cmd.padEnd(15))} ${theme.muted('-')} ${theme.info(description)}` ); } static printStatus(message, type = 'info') { const theme = this.getTheme(); const icons = { info: '🔹', success: '✅', warning: '⚠️', error: '❌', loading: '⏳' }; const color = theme[type] || theme.info; console.log(`\n${color(`${icons[type]} ${message}`)}`); } static printResult(title, content) { const theme = this.getTheme(); const resultBox = boxen( `${theme.success.bold(title)}\n\n${theme.info(content)}`, { padding: 1, margin: 1, borderStyle: 'single', borderColor: 'green', backgroundColor: 'black' } ); console.log(resultBox); } static printTable(headers, rows) { const theme = this.getTheme(); const colWidths = headers.map((header, index) => { const maxDataWidth = Math.max(...rows.map(row => String(row[index] || '').length)); return Math.max(header.length, maxDataWidth); }); const headerRow = headers.map((header, i) => theme.primary.bold(header.padEnd(colWidths[i])) ).join(' │ '); console.log(`\n${theme.accent('┌' + colWidths.map(w => '─'.repeat(w + 2)).join('┬') + '┐')}`); console.log(`${theme.accent('│')} ${headerRow} ${theme.accent('│')}`); console.log(`${theme.accent('├' + colWidths.map(w => '─'.repeat(w + 2)).join('┼') + '┤')}`); rows.forEach(row => { const dataRow = row.map((cell, i) => theme.info(String(cell).padEnd(colWidths[i])) ).join(' │ '); console.log(`${theme.accent('│')} ${dataRow} ${theme.accent('│')}`); }); console.log(`${theme.accent('└' + colWidths.map(w => '─'.repeat(w + 2)).join('┴') + '┘')}\n`); } } // -------------------- STARTUP FLAG -------------------- let hasShownStartup = false; // -------------------- LOGO -------------------- async function showLogo(config) { console.clear(); const theme = Interface.getTheme(); const currentTime = new Date().toLocaleString(); const weather = await getCurrentWeather(); const logo = boxen( `${theme.primary.bold(` ███████████ █████████ ███ ░░███░░░░░███ ███░░░░░███ ░░░ ░███ ░███ ██████ █████ ███ █████ ██████ ████████ ░███ ░███ ████ ░██████████ ███░░███░░███ ░███░░███ ███░░███░░███░░███ ░███████████ ░░███ ░███░░░░░░ ░███ ░███ ░███ ░███ ░███ ░███████ ░███ ░░░ ░███░░░░░███ ░███ ░███ ░███ ░███ ░░███████████ ░███░░░ ░███ ░███ ░███ ░███ █████ ░░██████ ░░████░████ ░░██████ █████ █████ █████ █████ ░░░░░ ░░░░░░ ░░░░ ░░░░ ░░░░░░ ░░░░░ ░░░░░ ░░░░░ ░░░░░ `)} ${theme.accent("═══════════════════════════════════════════════════════════")} ${theme.secondary.bold("POWER AI")} - ${theme.highlight("Ultimate Windows PowerShell AI Assistant")} ${theme.accent("═══════════════════════════════════════════════════════════")} ${theme.success("🕐 " + currentTime)} ${theme.muted("│")} ${theme.info(`🌡️ ${weather.temperature} │ 💧 ${weather.humidity} │ 💨 ${weather.windSpeed}`)} ${theme.success("📍 " + weather.location)} ${theme.muted("│")} ${theme.info(weather.description)} ${theme.muted("💬 Ask anything - I'll execute it")} `, { padding: 1, margin: 1, borderStyle: 'double', borderColor: 'magenta', backgroundColor: 'black' } ); console.log(logo); Interface.printHeader("🚀 POWER COMMANDS", "Windows system control and AI modes"); const powerCommands = [ ["psremote", "PowerShell Remoting management"], ["registry", "Registry operations"], ["scheduled-tasks", "Manage scheduled tasks"], ["reason", "Enable reasoning mode"], ["fast", "Enable fast mode"], ["voicetts", "Toggle voice TTS output"] ]; powerCommands.forEach(([cmd, desc]) => { Interface.printCommand(cmd, desc); }); Interface.printHeader("🔧 UTILITY COMMANDS", "Tools and configuration"); const utilityCommands = [ ["tmode", "Agentic Coding Mode (like Gemini CLI)"], ["network", "Advanced network analysis"], ["search", "Web search + AI analysis"], ["ask", "Chat with Gemini AI"], ["weather", "Get weather"], ["sysinfo", "System information"], ["learn", "Teach PowerAI"], ["memory", "View learned knowledge"], ["clear", "Clear screen + cleanup scripts"], ["cleanup", "Remove temp scripts only"], ["quit/exit", "Exit PowerAI"] ]; utilityCommands.forEach(([cmd, desc]) => { Interface.printCommand(cmd, desc); }); console.log(`\n${theme.muted(`Mode: ${config.reasoningMode ? 'REASONING' : 'FAST'} | OS: Windows`)}\n`); } // -------------------- WEATHER -------------------- async function getCurrentWeather(city = "Karachi") { try { const response = await fetch(`https://api.duckduckgo.com/?q=weather+${city}&format=json&no_redirect=1&no_html=1`); const data = await response.json(); if (data && data.Current) { const weather = data.Current; return { temperature: weather.Temperature + "°C", humidity: weather.Humidity + "%", windSpeed: weather.WindSpeed + " km/h", description: getWeatherEmoji(weather.Condition) + " " + weather.Condition, location: data.Heading || city }; } return getMockWeather(city); } catch (error) { return getMockWeather(city); } } function getMockWeather(city) { const now = new Date(); const hour = now.getHours(); const month = now.getMonth(); let description = "☀️ Clear"; if (month >= 11 || month <= 2) description = "❄️ Winter"; else if (month >= 3 && month <= 5) description = "🌷 Spring"; else if (month >= 6 && month <= 8) description = "☀️ Summer"; else description = "🍂 Autumn"; let temp = "25°C"; if (hour >= 22 || hour <= 6) temp = "18°C"; else if (hour >= 7 && hour <= 12) temp = "22°C"; else if (hour >= 13 && hour <= 18) temp = "30°C"; else temp = "25°C"; return { temperature: temp, humidity: "65%", windSpeed: "12 km/h", description: description, location: city }; } function getWeatherEmoji(condition) { if (!condition) return '🌤️'; const conditionLower = condition.toLowerCase(); if (conditionLower.includes('sunny') || conditionLower.includes('clear')) return '☀️'; if (conditionLower.includes('cloud')) return '☁️'; if (conditionLower.includes('rain')) return '🌧️'; if (conditionLower.includes('storm')) return '⛈️'; if (conditionLower.includes('snow')) return '❄️'; if (conditionLower.includes('fog') || conditionLower.includes('mist')) return '🌫️'; if (conditionLower.includes('wind')) return '💨'; return '🌤️'; } // -------------------- CONFIG -------------------- async function getConfig() { await fs.ensureDir(CONFIG_DIR); const defaultConfig = { apiKey: "", autoExecute: true, reasoningMode: true, voiceTTS: false }; if (!fs.existsSync(CONFIG_PATH)) { Interface.printHeader("🔧 POWERAI SETUP", "Let's get you configured"); const theme = Interface.getTheme(); const key = readlineSync.question(theme.primary("Enter your Gemini API key: ")); defaultConfig.apiKey = key; await fs.writeJson(CONFIG_PATH, defaultConfig); Interface.printStatus("Configuration saved!", 'success'); return defaultConfig; } const config = await fs.readJson(CONFIG_PATH); return { ...defaultConfig, ...config }; } async function saveConfig(config) { await fs.writeJson(CONFIG_PATH, config); } // -------------------- POWERSHELL REMOTING MANAGER -------------------- class PSRemotingManager { static async getPSRemoteConfig() { try { return await fs.readJson(PSREMOTE_CONFIG_PATH); } catch { return { sessions: [], trustedHosts: [] }; } } static async savePSRemoteConfig(config) { await fs.writeJson(PSREMOTE_CONFIG_PATH, config); } static async enablePSRemoting() { try { Interface.printStatus("Enabling PowerShell Remoting (requires Administrator)...", 'info'); const result = await execAsync('powershell.exe -NoProfile -Command "Enable-PSRemoting -Force"', { encoding: 'utf8' }); return `✅ PowerShell Remoting enabled\n${result.stdout}`; } catch (error) { return `❌ Failed to enable PSRemoting: ${error.message}\nRun PowerAI as Administrator`; } } static async addTrustedHost(host) { try { const psConfig = await this.getPSRemoteConfig(); const cmd = `powershell.exe -NoProfile -Command "Set-Item WSMan:\\localhost\\Client\\TrustedHosts -Value '${host}' -Concatenate -Force"`; await execAsync(cmd, { encoding: 'utf8' }); psConfig.trustedHosts.push({ host, added: new Date().toISOString() }); await this.savePSRemoteConfig(psConfig); return `✅ Added ${host} to TrustedHosts`; } catch (error) { return `❌ Failed to add trusted host: ${error.message}`; } } static async executeRemoteCommand(computerName, command, credential = null) { try { let psCmd = `powershell.exe -NoProfile -Command "Invoke-Command -ComputerName ${computerName} -ScriptBlock { ${command} }"`; if (credential) { psCmd = `powershell.exe -NoProfile -Command "$cred = Get-Credential -UserName '${credential.username}' -Message 'Enter password'; Invoke-Command -ComputerName ${computerName} -Credential $cred -ScriptBlock { ${command} }"`; } const result = await execAsync(psCmd, { encoding: 'utf8', maxBuffer: 10 * 1024 * 1024 }); return { success: true, output: result.stdout, error: result.stderr }; } catch (error) { return { success: false, output: "", error: error.message }; } } static async listSessions() { try { const result = await execAsync('powershell.exe -NoProfile -Command "Get-PSSession"', { encoding: 'utf8' }); return result.stdout; } catch (error) { return "No active sessions"; } } static async displayPSRemoteInfo() { const theme = Interface.getTheme(); const psConfig = await this.getPSRemoteConfig(); Interface.printHeader("🔐 POWERSHELL REMOTING", "Remote Windows management"); console.log(theme.info("\n📌 Quick Commands:")); console.log(theme.secondary(" • Enable PSRemoting: ") + theme.highlight("Enable-PSRemoting -Force")); console.log(theme.secondary(" • Add Trusted Host: ") + theme.highlight("Set-Item WSMan:\\localhost\\Client\\TrustedHosts -Value 'hostname'")); console.log(theme.secondary(" • Remote Command: ") + theme.highlight("Invoke-Command -ComputerName host -ScriptBlock {}")); if (psConfig.trustedHosts.length > 0) { Interface.printSection("TRUSTED HOSTS", `${psConfig.trustedHosts.length} configured`); psConfig.trustedHosts.forEach((th, i) => { console.log(` ${theme.secondary(`${i + 1}.`)} ${theme.info(th.host)} ${theme.muted(`- Added: ${new Date(th.added).toLocaleDateString()}`)}`); }); } console.log(theme.info("\n📖 PowerShell Remoting Ports:")); console.log(theme.secondary(" • HTTP: ") + theme.highlight("5985")); console.log(theme.secondary(" • HTTPS: ") + theme.highlight("5986\n")); } } // -------------------- WINDOWS REGISTRY MANAGER -------------------- class RegistryManager { static async readRegistry(keyPath, valueName = null) { try { let cmd = `powershell.exe -NoProfile -Command "Get-ItemProperty -Path '${keyPath}'"`; if (valueName) { cmd = `powershell.exe -NoProfile -Command "(Get-ItemProperty -Path '${keyPath}').${valueName}"`; } const result = await execAsync(cmd, { encoding: 'utf8' }); return result.stdout.trim(); } catch (error) { return `❌ Registry read failed: ${error.message}`; } } static async writeRegistry(keyPath, valueName, value, valueType = 'String') { try { const checkCmd = `powershell.exe -NoProfile -Command "Get-ItemProperty -Path '${keyPath}' -Name '${valueName}' -ErrorAction SilentlyContinue"`; const checkResult = await execAsync(checkCmd, { encoding: 'utf8' }).catch(() => null); let cmd; if (checkResult && checkResult.stdout) { cmd = `powershell.exe -NoProfile -Command "Set-ItemProperty -Path '${keyPath}' -Name '${valueName}' -Value '${value}'"`; } else { cmd = `powershell.exe -NoProfile -Command "New-ItemProperty -Path '${keyPath}' -Name '${valueName}' -Value '${value}' -PropertyType ${valueType} -Force"`; } await execAsync(cmd, { encoding: 'utf8' }); return `✅ Registry value set: ${keyPath}\\${valueName} = ${value}`; } catch (error) { return `❌ Registry write failed: ${error.message}`; } } static async createRegistryKey(keyPath) { try { const cmd = `powershell.exe -NoProfile -Command "New-Item -Path '${keyPath}' -Force"`; await execAsync(cmd, { encoding: 'utf8' }); return `✅ Registry key created: ${keyPath}`; } catch (error) { return `❌ Registry key creation failed: ${error.message}`; } } static async displayRegistryHelp() { const theme = Interface.getTheme(); Interface.printHeader("📝 WINDOWS REGISTRY", "Safe registry operations"); console.log(theme.warning("\n⚠️ WARNING: Modifying registry can damage Windows. Be careful!\n")); console.log(theme.info("Common Registry Hives:")); console.log(theme.secondary(" • HKEY_CURRENT_USER (HKCU): ") + theme.highlight("Current user settings")); console.log(theme.secondary(" • HKEY_LOCAL_MACHINE (HKLM): ") + theme.highlight("System-wide settings")); console.log(theme.secondary(" • HKEY_CLASSES_ROOT (HKCR): ") + theme.highlight("File associations")); console.log(theme.info("\n📌 Example Commands:")); console.log(theme.secondary(" Read: ") + theme.highlight("Get-ItemProperty -Path 'HKCU:\\Software\\Microsoft\\Windows'")); console.log(theme.secondary(" Write: ") + theme.highlight("Set-ItemProperty -Path 'HKCU:\\...' -Name 'Value' -Value 'Data'")); console.log(theme.secondary(" Create: ") + theme.highlight("New-Item -Path 'HKCU:\\Software\\MyApp'\n")); } } // -------------------- SCHEDULED TASKS MANAGER -------------------- class ScheduledTasksManager { static async listTasks() { try { const cmd = 'powershell.exe -NoProfile -Command "Get-ScheduledTask | Select-Object TaskName, State, TaskPath | Format-Table -AutoSize"'; const result = await execAsync(cmd, { encoding: 'utf8', maxBuffer: 10 * 1024 * 1024 }); return result.stdout; } catch (error) { return `❌ Failed to list tasks: ${error.message}`; } } static async createTask(taskName, command, trigger = 'Daily', startTime = '09:00') { try { const timeTriggers = ['Daily', 'Weekly', 'Once']; const triggerParam = timeTriggers.includes(trigger) ? `New-ScheduledTaskTrigger -${trigger} -At ${startTime}` : `New-ScheduledTaskTrigger -${trigger}`; const cmd = `powershell.exe -NoProfile -Command "$action = New-ScheduledTaskAction -Execute '${command}'; $trigger = ${triggerParam}; Register-ScheduledTask -TaskName '${taskName}' -Action $action -Trigger $trigger"`; await execAsync(cmd, { encoding: 'utf8' }); return `✅ Scheduled task '${taskName}' created`; } catch (error) { return `❌ Task creation failed: ${error.message}`; } } static async deleteTask(taskName) { try { const cmd = `powershell.exe -NoProfile -Command "Unregister-ScheduledTask -TaskName '${taskName}' -Confirm:$false"`; await execAsync(cmd, { encoding: 'utf8' }); return `✅ Scheduled task '${taskName}' deleted`; } catch (error) { return `❌ Task deletion failed: ${error.message}`; } } static async displayTasksInfo() { const theme = Interface.getTheme(); Interface.printHeader("⏰ SCHEDULED TASKS", "Windows Task Scheduler management"); console.log(theme.info("\n📌 Quick Commands:")); console.log(theme.secondary(" • List all: ") + theme.highlight("Get-ScheduledTask")); console.log(theme.secondary(" • Create: ") + theme.highlight("Register-ScheduledTask")); console.log(theme.secondary(" • Delete: ") + theme.highlight("Unregister-ScheduledTask")); console.log(theme.secondary(" • Run now: ") + theme.highlight("Start-ScheduledTask -TaskName 'name'")); console.log(theme.info("\n🔄 Trigger Types:")); console.log(theme.secondary(" • Daily, Weekly, AtLogon, AtStartup, OnIdle\n")); } } // -------------------- RAG KNOWLEDGE SYSTEM -------------------- class RAGSystem { static async getKnowledge() { try { return await fs.readJson(KNOWLEDGE_PATH); } catch { return { facts: [], commands: [], solutions: [], userPreferences: [] }; } } static async saveKnowledge(knowledge) { await fs.writeJson(KNOWLEDGE_PATH, knowledge); } static async learnNewInfo(category, information) { const knowledge = await this.getKnowledge(); if (!knowledge[category]) { knowledge[category] = []; } knowledge[category].push({ info: information, timestamp: new Date().toISOString(), usageCount: 0 }); await this.saveKnowledge(knowledge); return knowledge; } static async searchKnowledge(query, category = null) { const knowledge = await this.getKnowledge(); const results = []; const queryLower = query.toLowerCase(); const categories = category ? [category] : ['facts', 'commands', 'solutions', 'userPreferences']; categories.forEach(cat => { if (knowledge[cat]) { knowledge[cat].forEach(item => { if (item.info.toLowerCase().includes(queryLower)) { results.push({ category: cat, ...item }); } }); } }); return results.slice(0, 5); } static async displayKnowledge() { const knowledge = await this.getKnowledge(); const theme = Interface.getTheme(); let totalItems = 0; Object.keys(knowledge).forEach(cat => { totalItems += knowledge[cat].length; }); if (totalItems === 0) { Interface.printStatus("No knowledge stored yet. Use 'learn' to add information.", 'warning'); return; } Interface.printHeader("📚 LEARNED KNOWLEDGE", `Total items: ${totalItems}`); Object.keys(knowledge).forEach(category => { if (knowledge[category].length > 0) { Interface.printSection(category.toUpperCase(), `${knowledge[category].length} items`); knowledge[category].forEach((item, index) => { console.log(` ${theme.secondary(`${index + 1}.`)} ${theme.info(item.info)}`); console.log(` ${theme.muted(`Used ${item.usageCount || 0} times • ${new Date(item.timestamp).toLocaleDateString()}`)}\n`); }); } }); } } // -------------------- WEB SEARCH -------------------- class EnhancedWebSearch { static async search(query, maxResults = 5) { const spinner = ora({ text: Interface.getTheme().secondary("🔍 Searching the web..."), spinner: 'dots' }).start(); try { const response = await fetch(`https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_redirect=1&no_html=1`); const data = await response.json(); spinner.stop(); return this.parseResults(data, maxResults); } catch (error) { spinner.stop(); Interface.printStatus("Search failed: " + error.message, 'error'); return []; } } static parseResults(data, maxResults) { const results = []; if (data.RelatedTopics) { data.RelatedTopics.forEach(topic => { if (topic.FirstURL && topic.Text && results.length < maxResults) { results.push({ title: topic.Text, url: topic.FirstURL, snippet: topic.Text.slice(0, 150) + '...' }); } }); } if (data.Results && results.length < maxResults) { data.Results.forEach(result => { if (result.FirstURL && result.Text && results.length < maxResults) { results.push({ title: result.Text, url: result.FirstURL, snippet: result.Text.slice(0, 150) + '...' }); } }); } return results; } static async displaySearchResults(query, results, aiAnalysis) { const theme = Interface.getTheme(); Interface.printHeader("🔍 SEARCH RESULTS", `Query: "${query}"`); if (results.length === 0) { Interface.printStatus("No results found", 'warning'); return; } results.forEach((result, index) => { console.log(`\n${theme.primary(`${index + 1}.`)} ${theme.highlight(result.title)}`); console.log(`${theme.muted('🔗 ' + result.url)}`); console.log(`${theme.info('📝 ' + result.snippet)}\n`); }); if (aiAnalysis) { Interface.printResult("🧠 AI ANALYSIS", aiAnalysis); } } } // Code generation features removed for simplified version // -------------------- REASONING ENGINE -------------------- class ReasoningEngine { static async generateReasoningResponse(model, userInput, config) { try { const knowledge = await RAGSystem.searchKnowledge(userInput); const knowledgeContext = knowledge.length > 0 ? `\nRelevant knowledge: ${knowledge.map(k => k.info).join('; ')}` : ''; const prompt = ` You are PowerAI, an advanced Windows PowerShell AI assistant running on Windows. User request: "${userInput}"${knowledgeContext} ANALYZE THIS REQUEST AND: 1. Break down what the user wants step-by-step 2. Identify if it requires PowerShell commands, system operations, or other actions 3. Explain your reasoning process 4. Provide the recommended approach 5. List any potential risks or considerations Be concise but thorough. Format your response clearly. `; const result = await model.generateContent(prompt); return result.response.text(); } catch (error) { return `Analysis failed: ${error.message}`; } } } // -------------------- SCRIPT MANAGER -------------------- class ScriptManager { static SCRIPTS_DIR = path.join(CONFIG_DIR, "scripts"); static async ensureScriptsDir() { await fs.ensureDir(this.SCRIPTS_DIR); } static async createTempScript(language, code, packages = []) { await this.ensureScriptsDir(); const timestamp = Date.now(); const scriptName = `temp_${timestamp}`; let scriptPath, packageInstallCmd, runCmd; switch (language.toLowerCase()) { case 'python': case 'py': scriptPath = path.join(this.SCRIPTS_DIR, `${scriptName}.py`); await fs.writeFile(scriptPath, code); if (packages.length > 0) { packageInstallCmd = `python -m pip install ${packages.join(' ')} --quiet --target "${this.SCRIPTS_DIR}"`; } runCmd = `python "${scriptPath}"`; break; case 'javascript': case 'node': case 'js': scriptPath = path.join(this.SCRIPTS_DIR, `${scriptName}.js`); await fs.writeFile(scriptPath, code); if (packages.length > 0) { const packageJsonPath = path.join(this.SCRIPTS_DIR, 'package.json'); if (!await fs.pathExists(packageJsonPath)) { await fs.writeJson(packageJsonPath, { name: "powerai-scripts", version: "1.0.0" }); } packageInstallCmd = `cd "${this.SCRIPTS_DIR}" && npm install ${packages.join(' ')} --silent`; } runCmd = `node "${scriptPath}"`; break; case 'go': case 'golang': scriptPath = path.join(this.SCRIPTS_DIR, `${scriptName}.go`); await fs.writeFile(scriptPath, code); if (packages.length > 0) { packageInstallCmd = `cd "${this.SCRIPTS_DIR}" && go get ${packages.join(' ')}`; } runCmd = `cd "${this.SCRIPTS_DIR}" && go run "${scriptName}.go"`; break; case 'ruby': case 'rb': scriptPath = path.join(this.SCRIPTS_DIR, `${scriptName}.rb`); await fs.writeFile(scriptPath, code); if (packages.length > 0) { packageInstallCmd = `gem install ${packages.join(' ')} --install-dir "${this.SCRIPTS_DIR}"`; } runCmd = `ruby "${scriptPath}"`; break; default: throw new Error(`Unsupported language: ${language}`); } return { scriptPath, packageInstallCmd, runCmd }; } static async executeScript(language, code, packages = []) { try { const { scriptPath, packageInstallCmd, runCmd } = await this.createTempScript(language, code, packages); if (packageInstallCmd) { Interface.printStatus(`Installing packages: ${packages.join(', ')}...`, 'info'); try { const installResult = await execAsync(packageInstallCmd, { encoding: 'utf8', maxBuffer: 10 * 1024 * 1024 }); Interface.printStatus(`Packages installed successfully`, 'success'); } catch (installError) { Interface.printStatus(`Package install warning: ${installError.message}`, 'warning'); } } const result = await execAsync(runCmd, { encoding: 'utf8', maxBuffer: 10 * 1024 * 1024, env: { ...process.env, PYTHONPATH: this.SCRIPTS_DIR, NODE_PATH: this.SCRIPTS_DIR, PATH: `${this.SCRIPTS_DIR};${process.env.PATH}` } }); return result.stdout || result.stderr || "✅ Script executed successfully"; } catch (error) { return `❌ Script execution error: ${error.message}\n${error.stderr || ''}`; } } static async cleanupScripts() { try { await fs.remove(this.SCRIPTS_DIR); await this.ensureScriptsDir(); return "✅ All temporary scripts cleaned up"; } catch (error) { return `⚠️ Cleanup warning: ${error.message}`; } } } // -------------------- NETWORK ANALYZER -------------------- class NetworkAnalyzer { static async scanNetwork(target = null) { Interface.printStatus("Running comprehensive network analysis...", 'info'); const results = { interfaces: "", connections: "", ports: "", wifi: "", routing: "" }; try { results.interfaces = await UniversalExecutor.executeSystemCommand( "Get-NetAdapter | Select-Object Name, Status, LinkSpeed, MacAddress, InterfaceDescription | Format-Table -AutoSize" ); results.connections = await UniversalExecutor.executeSystemCommand( "Get-NetTCPConnection | Where-Object {$_.State -eq 'Established'} | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State | Format-Table -AutoSize" ); results.ports = await UniversalExecutor.executeSystemCommand( "Get-NetTCPConnection | Select-Object LocalPort, State | Group-Object LocalPort | Select-Object Name, Count | Sort-Object Count -Descending | Select-Object -First 10" ); results.wifi = await UniversalExecutor.executeSystemCommand( "netsh wlan show networks mode=bssid" ); results.routing = await UniversalExecutor.executeSystemCommand( "Get-NetRoute | Where-Object {$_.DestinationPrefix -eq '0.0.0.0/0'} | Select-Object DestinationPrefix, NextHop, RouteMetric | Format-Table -AutoSize" ); if (target) { results.ping = await UniversalExecutor.executeSystemCommand( `Test-NetConnection -ComputerName ${target} -InformationLevel Detailed` ); } return results; } catch (error) { return { error: `Network scan failed: ${error.message}` }; } } static async advancedNetworkScan(scanType = 'full') { const theme = Interface.getTheme(); Interface.printHeader("🌐 ADVANCED NETWORK ANALYSIS", "AI-powered network intelligence"); const pythonCode = ` import socket import json from datetime import datetime def scan_ports(host, ports): open_ports = [] for port in ports: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(0.5) result = sock.connect_ex((host, port)) if result == 0: open_ports.append(port) sock.close() return open_ports def get_local_ip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) local_ip = s.getsockname()[0] s.close() return local_ip except: return "Unable to determine" common_ports = [21, 22, 23, 25, 53, 80, 443, 3306, 3389, 5432, 8080] local_ip = get_local_ip() print(f"Local IP: {local_ip}") print(f"Scanning common ports on localhost...") open_ports = scan_ports('127.0.0.1', common_ports) print(f"Open ports: {open_ports if open_ports else 'None'}") `; try { const scriptResult = await ScriptManager.executeScript('python', pythonCode, ['socket']); Interface.printSection("PYTHON NETWORK SCAN", "Port analysis complete"); console.log(theme.info(scriptResult)); const basicScan = await this.scanNetwork(); Interface.printSection("NETWORK INTERFACES", "Active adapters"); console.log(theme.info(basicScan.interfaces)); Interface.printSection("ACTIVE CONNECTIONS", "Established TCP connections"); console.log(theme.info(basicScan.connections)); Interface.printSection("TOP PORTS", "Most used local ports"); console.log(theme.info(basicScan.ports)); return "✅ Network analysis complete"; } catch (error) { return `❌ Advanced scan failed: ${error.message}`; } } } // -------------------- UNIVERSAL EXECUTOR -------------------- class UniversalExecutor { static async executeSystemCommand(command) { try { const psCommand = `powershell.exe -NoProfile -Command "${command.replace(/"/g, '\\"')}"`; const result = await execAsync(psCommand, { encoding: 'utf8', maxBuffer: 10 * 1024 * 1024 }); return result.stdout || result.stderr || "✅ Command executed successfully"; } catch (error) { return `❌ Error: ${error.message}\n${error.stderr || ''}`; } } static async executePowerShell(command) { return await this.executeSystemCommand(command); } static async executeAnyCommand(userInput, model) { const spinner = ora({ text: Interface.getTheme().secondary("🤖 AI analyzing command..."), spinner: 'dots' }).start(); try { const knowledge = await RAGSystem.searchKnowledge(userInput); const knowledgeContext = knowledge.length > 0 ? `Relevant knowledge: ${knowledge.map(k => k.info).join('; ')}` : ''; const prompt = ` You are PowerAI running on Windows. User wants: "${userInput}" ${knowledgeContext} ANALYZE AND RESPOND WITH JSON: { "commands": [ { "type": "powershell|registry|scheduled-task|psremote|file|system", "command": "exact_command_to_execute", "description": "what_this_does" } ], "explanation": "brief_explanation_of_actions" } TYPES: - powershell: PowerShell commands - registry: Registry operations - scheduled-task: Task scheduler - psremote: Remote PowerShell - file: File operations - system: System commands Return ONLY JSON, no other text. `; const result = await model.generateContent(prompt); const response = result.response.text(); spinner.stop(); const jsonMatch = response.match(/\{[\s\S]*\}/); if (!jsonMatch) { return await this.executeSystemCommand(userInput); } const aiPlan = JSON.parse(jsonMatch[0]); if (aiPlan.explanation) { Interface.printStatus(aiPlan.explanation, 'info'); } const results = []; for (const cmd of aiPlan.commands) { try { let output = ""; switch (cmd.type) { case "powershell": case "system": output = await this.executeSystemCommand(cmd.command); break; case "registry": const regMatch = cmd.command.match(/(read|write|create)\s+(.*)/i); if (regMatch) { const [, action, params] = regMatch; if (action.toLowerCase() === 'read') { const parts = params.split(' '); output = await RegistryManager.readRegistry(parts[0], parts[1]); } else if (action.toLowerCase() === 'write') { const parts = params.split(' '); output = await RegistryManager.writeRegistry(parts[0], parts[1], parts[2], parts[3] || 'String'); } else if (action.toLowerCase() === 'create') { output = await RegistryManager.createRegistryKey(params); } } break; case "scheduled-task": const taskMatch = cmd.command.match(/(create|delete|list)\s+(.*)/i); if (taskMatch) { const [, action, params] = taskMatch; if (action.toLowerCase() === 'create') { const parts = params.split(' '); output = await ScheduledTasksManager.createTask(parts[0], parts[1], parts[2], parts[3]); } else if (action.toLowerCase() === 'delete') { output = await ScheduledTasksManager.deleteTask(params); } else if (action.toLowerCase() === 'list') { output = await ScheduledTasksManager.listTasks(); } } break; case "psremote": const remoteMatch = cmd.command.match(/([^\s:]+):\s*(.+)/); if (remoteMatch) { const result = await PSRemotingManager.executeRemoteCommand(remoteMatch[1], remoteMatch[2]); output = result.success ? result.output : result.error; } break; case "file": if (cmd.command.includes("create")) { const fileMatch = cmd.command.match(/create\s+([^\s]+)/); if (fileMatch) { await fs.ensureFile(fileMatch[1]); output = `✅ Created file: ${fileMatch[1]}`; } } break; default: output = await this.executeSystemCommand(cmd.command); } results.push(`✅ ${cmd.description}: ${output}`); } catch (error) { results.push(`❌ ${cmd.description}: ${error.message}`); } } return `🎯 Execution Complete:\n${results.join('\n')}`; } catch (error) { spinner.stop(); return `❌ Command execution failed: ${error.message}`; } } static async smartExecute(userInput, model) { const lowerInput = userInput.toLowerCase(); if (lowerInput.includes("powershell") || lowerInput.includes("get-") || lowerInput.includes("set-") || lowerInput.includes("invoke-")) { Interface.printStatus("Auto-executing PowerShell command...", 'info'); return await this.executePowerShell(userInput); } if (lowerInput.includes("enable psremoting") || lowerInput.includes("enable-psremoting")) { return await PSRemotingManager.enablePSRemoting(); } if (lowerInput.includes("add trusted") || lowerInput.includes("trustedhost")) { const hostMatch = userInput.match(/(?:host|trustedhost)\s+([^\s]+)/i); if (hostMatch) { return await PSRemotingManager.addTrustedHost(hostMatch[1]); } } if (lowerInput.includes("remote command") || lowerInput.includes("invoke-command")) { const match = userInput.match(/(?:on|computer)\s+([^\s]+)\s+(?:run|execute|command)\s+(.+)/i); if (match) { const result = await PSRemotingManager.executeRemoteCommand(match[1], match[2]); return result.success ? result.output : result.error; } } if (lowerInput.includes("system info") || lowerInput.includes("sysinfo")) { Interface.printStatus("Gathering system information...", 'info'); const commands = [ "systeminfo", "Get-ComputerInfo | Select-Object WindowsVersion, OsArchitecture, CsManufacturer, CsModel", "Get-PhysicalDisk | Select-Object DeviceId, FriendlyName, Size, MediaType", "Get-NetIPAddress | Where-Object {$_.AddressFamily -eq 'IPv4' -and $_.InterfaceAlias -notlike '*Loopback*'}" ]; let result = "📊 System Information:\n\n"; for (const cmd of commands) { result += `=== ${cmd.split('|')[0].trim()} ===\n`; result += await this.executeSystemCommand(cmd) + "\n\n"; } return result; } if (lowerInput.includes("network scan") || lowerInput.includes("check network") || lowerInput.includes("network analysis")) { return await NetworkAnalyzer.advancedNetworkScan(); } if (lowerInput.includes("run script") || lowerInput.includes("execute script")) { const langMatch = userInput.match(/(?:python|node|go|ruby|js)/i); const language = langMatch ? langMatch[0] : 'python'; Interface.printStatus(`Creating temporary ${language} script...`, 'info'); const scriptPrompt = `Create a ${language} script for: ${userInput}. Return ONLY the code, no explanations.`; const codeResult = await model.generateContent(scriptPrompt); const code = codeResult.response.text().replace(/```[\w]*\n?/g, '').trim(); const packagesMatch = userInput.match(/(?:install|use|import)\s+([a-zA-Z0-9_\-,\s]+)/); const packages = packagesMatch ? packagesMatch[1].split(/[,\s]+/).filter(p => p) : []; return await ScriptManager.executeScript(language, code, packages); } if (lowerInput.includes("create file") || lowerInput.includes("make file")) { const fileMatch = userInput.match(/(?:create|make)\s+file\s+([^\s]+)/i); if (fileMatch) { const fileName = fileMatch[1]; await fs.ensureFile(fileName); return `✅ Created file: ${fileName}`; } } return await this.executeAnyCommand(userInput, model); } } // -------------------- TTS HELPER -------------------- class TTSHelper { static async speak(text) { return new Promise((resolve) => { const cleanText = text.replace(/[`*#_~]/g, '').replace(/\n/g, '. '); const psCommand = ` Add-Type -AssemblyName System.speech $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer $speak.Rate = 1 $speak.Volume = 100 $speak.Speak('${cleanText.replace(/'/g, "''")}') $speak.Dispose() `.replace(/'/g, "''"); exec(`powershell.exe -NoProfile -Command "${psCommand}"`, (error) => { resolve(); }); }); } } // -------------------- PROJECT MANAGER -------------------- class ProjectManager { static PROJECTS_DIR = path.join(CONFIG_DIR, "projects"); static async ensureProjectsDir() { await fs.ensureDir(this.PROJECTS_DIR); } static async saveProject(projectName, plan) { await this.ensureProjectsDir(); const projectPath = path.join(this.PROJECTS_DIR, `${projectName}.json`); await fs.writeJson(projectPath, { name: projectName, plan: plan, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }); return projectPath; } static async loadProject(projectName) { const projectPath = path.join(this.PROJECTS_DIR, `${projectName}.json`); if (await fs.pathExists(projectPath)) { return await fs.readJson(projectPath); } return null; } static async listProjects() { await this.ensureProjectsDir(); const files = await fs.readdir(this.PROJECTS_DIR); const projects = []; for (const file of files) { if (file.endsWith('.json')) { const project = await fs.readJson(path.join(this.PROJECTS_DIR, file)); projects.push({ name: project.name, createdAt: project.createdAt, steps: project.plan?.steps?.length || 0 }); } } return projects; } } // -------------------- NODE.JS FILE OPERATIONS -------------------- class NodeFileOps { static async createFile(filePath, content = '') { try { await fs.ensureFile(filePath); if (content) { await fs.writeFile(filePath, content, 'utf8'); } return `✅ Created: ${filePath} (${content.length} bytes)`; } catch (error) { return `❌ Create failed: ${error.message}`; } } static async editFile(filePath, content) { try { await fs.writeFile(filePath, content, 'utf8'); return `✅ Updated: ${filePath} (${content.length} bytes)`; } catch (error) { return `❌ Edit failed: ${error.message}`; } } static async readFile(filePath) { try { const content = await fs.readFile(filePath, 'utf8'); return content; } catch (error) { return `❌ Read failed: ${error.message}`; } } static async createFolder(folderPath) { try { await fs.ensureDir(folderPath); return `✅ Folder created: ${folderPath}`; } catch (error) { return `❌ Folder creation failed: ${error.message}`; } } static async deleteFile(filePath) { try { await fs.remove(filePath); return `✅ Deleted: ${filePath}`; } catch (error) { return `❌ Delete failed: ${error.message}`; } } } // -------------------- AGENTIC CODING MODE (T MODE) -------------------- class AgenticCodingMode { static async start(reasoningModel, config) { console.clear(); const theme = Interface.getTheme(); // T Mode has its own interface - like Gemini CLI const tmodeHeader = boxen( `${theme.primary.bold(` __ __| \ ___| | / \ | _ \ __ \ ____| | _ \ \___ \ ' / |\/ | | | | | __| | ___ \ | . \ | | | | | | | _| _/ _\ _____/ _|\_\ _| _| \___/ ____/ _____| `)} ${theme.accent("═══════════════════════════════════════════════════════")} ${theme.secondary.bold("AGENTIC CODING MODE")} - ${theme.highlight("AI-Powered Project Development")} ${theme.accent("═══════════════════════════════════════════════════════")} ${theme.info("🤖 Autonomous AI agent for complete project generation")} ${theme.muted("Build websites, apps, scripts, and full-stack applications")} `, { padding: 1, margin: 1, borderStyle: 'double', borderColor: 'cyan', backgroundColor: 'black' } ); console.log(tmodeHeader); // Show available projects const projects = await ProjectManager.listProjects(); if (projects.length > 0) { console.log(theme.accent("\n📂 Your Projects:")); projects.forEach((p, i) => { console.log(` ${theme.secondary(`${i + 1}.`)} ${theme.info(p.name)} ${theme.muted(`- ${p.steps} steps - ${new Date(p.createdAt).toLocaleDateString()}`)}`); }); } console.log(theme.primary("\n🎯 Commands:")); console.log(theme.info(" [n] - Start new project")); console.log(theme.info(" [p] - Load previous project")); console.log(theme.info(" [quit] - Exit to PowerAI CLI\n")); const choice = readlineSync.question(theme.primary("T Mode> ")).toLowerCase(); if (choice === 'quit') { console.clear(); Interface.printStatus("Returned to PowerAI CLI", 'info'); return; } let projectName = ""; let taskDescription = ""; let existingPlan = null; if (choice === 'p' && projects.length > 0) { projectName = readlineSync.question(theme.primary("Project name: ")); const selectedProject = projects.find(p => p.name.toLowerCase() === projectName.toLowerCase()); if (selectedProject) { const loadedProject = await ProjectManager.loadProject(selectedProject.name); existingPlan = loadedProject.plan; taskDescription = loadedProject.plan.description; Interface.printStatus(`✅ Loaded: ${selectedProject.name}`, 'success'); } else { Interface.printStatus("Project not found", 'error'); return; } } else { projectName = readlineSync.question(theme.primary("Project name: ")); taskDescription = readlineSync.question(theme.primary("What do you want to build: ")); } const spinner = ora({ text: theme.secondary("🧠 AI planning project..."), spinner: 'dots' }).start(); try { let plan; if (existingPlan) { plan = existingPlan; spinner.stop(); } else { const planResponse = await reasoningModel.generateContent(` You are an autonomous AI coding agent in T Mode. Generate a complete development plan. PROJECT: "${projectName}" REQUEST: "${taskDescription}" Create a comprehensive plan with all files, code, and setup steps. RESPOND WITH JSON: { "projectType": "website|webapp|script|api|fullstack|automation", "projectName": "${projectName}", "description": "what will be built", "steps": [ { "number": 1, "description": "step description", "type": "create_file|edit_file|create_folder|install_package|shell_command", "filePath": "path/to/file (if file operation)", "fileContent": "COMPLETE file content - NO PLACEHOLDERS", "command": "shell command (if shell_command type)", "language": "language name" } ] } CRITICAL RULES: - NEVER use ellipsis (...) or placeholders - Include COMPLETE file contents - Create proper folder structure - Include ALL dependencies (package.json, requirem