trace.ai-cli
Version:
A powerful AI-powered CLI tool
571 lines (511 loc) • 28.3 kB
JavaScript
const fetch = require('node-fetch');
const { encryptData, decryptData } = require('../utils/encryption');
const { getSystemInfo, formatBytes } = require('./systemInfoService');
/**
* Use AI to determine what system information is being requested
* @param {string} prompt - The user's prompt
* @param {Object} basicInfo - Basic system information for context
* @returns {Object} Object containing the determined query
*/
async function determineSystemInfoQuery(prompt, basicInfo) {
try {
// Create a prompt for the AI to analyze the user's query
const analysisPrompt = `Analyze the user's query: "${prompt}" and determine which system information they need.`;
// Use the AI to analyze the query
const models = ['kimi', 'mvrk', 'gma3'];
const modelRequests = models.map(model =>
fetch('https://traceai.dukeindustries7.workers.dev/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: encryptData({
a: model,
q: analysisPrompt,
r: [],
i: [],
c: JSON.stringify(basicInfo)
})
})
.then(res => res.text())
.then(text => {
try {
return decryptData(text);
} catch (e) {
console.error('Error decrypting data:', e.message);
return { text: null };
}
})
.catch(err => {
console.error('Error in model request:', err.message);
return { text: null };
})
);
const responses = await Promise.all(modelRequests);
// Ensure we have valid responses and filter out any null or undefined values
const validResponses = responses.filter(r => r && typeof r === 'object');
const responseTexts = validResponses
.filter(r => r.text && typeof r.text === 'string') // Ensure text exists and is a string
.map(r => r.text);
// Combine the responses to get the most accurate determination
let categories = new Set();
// Check if we have any valid responses
if (responseTexts && responseTexts.length > 0) {
for (const text of responseTexts) {
if (text && typeof text === 'string') {
const words = text.toLowerCase().trim().split(/\s+/);
for (const word of words) {
if (word && ['basic', 'cpu', 'memory', 'disk', 'network', 'process', 'environment', 'all'].includes(word)) {
categories.add(word);
}
}
}
}
} else {
// No valid responses, default to basic
console.log('No valid AI responses for system info query, defaulting to basic');
categories.add('basic');
}
// If 'all' is included, just return that
if (categories.has('all')) {
return { query: 'all' };
}
// If no categories were determined, default to basic
if (categories.size === 0) {
categories.add('basic');
}
// Convert the set to a space-separated string
const query = Array.from(categories).join(' ');
return { query };
} catch (error) {
console.error('❌ Error determining system info query:', error.message);
// Default to basic info if there's an error
return { query: 'basic' };
}
}
/**
* Check if a prompt is related to system information
* @param {string} prompt - The user's prompt
* @returns {boolean} True if the prompt is related to system information
*/
function isSystemInfoQuery(prompt) {
// Always return true for /system commands - we'll let the AI determine relevance
return true;
}
/**
* Format system information into a readable response
* @param {Object} sysInfo - System information object
* @param {string} prompt - The original prompt
* @returns {string} Formatted response
*/
function formatSystemInfoResponse(sysInfo, prompt) {
let response = `Here's the system information you requested:\n\n`;
// Check if we have any system information
const hasInfo = Object.keys(sysInfo).length > 0;
if (!hasInfo) {
response = `I couldn't find specific system information for your query: "${prompt}"\n\n`;
response += `You can ask about:\n`;
response += `- Basic system information (platform, architecture, hostname, manufacturer, model)\n`;
response += `- CPU information (model, cores, speed, load, temperature, manufacturer)\n`;
response += `- Memory information (total, used, free, active, available, swap)\n`;
response += `- Disk information (size, used, available, file systems, block devices)\n`;
response += `- Network information (interfaces, IP addresses, connections, wifi, latency)\n`;
response += `- Process information (running processes, services, resource usage)\n`;
response += `- Environment variables (PATH, SHELL, user info, etc.)\n\n`;
response += `Try queries like:\n`;
response += `- "What's my IP address?" (network)\n`;
response += `- "How much disk space do I have?" (disk)\n`;
response += `- "What's my CPU usage?" (cpu)\n`;
response += `- "Show me all system information" (all)\n\n`;
return response;
}
if (sysInfo.basic) {
const basic = sysInfo.basic;
response += `📱 **System Overview**\n`;
response += `- Platform: ${basic.platform} (${basic.type} ${basic.release})\n`;
response += `- Architecture: ${basic.arch}\n`;
response += `- Hostname: ${basic.hostname}\n`;
response += `- Uptime: ${Math.floor(basic.uptime / 3600)} hours ${Math.floor((basic.uptime % 3600) / 60)} minutes\n`;
// Add enhanced system information if available
if (basic.manufacturer) response += `- Manufacturer: ${basic.manufacturer}\n`;
if (basic.model) response += `- Model: ${basic.model}\n`;
if (basic.version) response += `- Version: ${basic.version}\n`;
if (basic.serial) response += `- Serial Number: ${basic.serial}\n`;
if (basic.uuid) response += `- UUID: ${basic.uuid}\n`;
if (basic.sku) response += `- SKU: ${basic.sku}\n`;
if (basic.virtual) response += `- Virtualization: ${basic.virtual ? 'Yes' : 'No'}\n`;
if (basic.distro) response += `- Distribution: ${basic.distro}\n`;
if (basic.codename) response += `- Codename: ${basic.codename}\n`;
if (basic.kernel) response += `- Kernel: ${basic.kernel}\n`;
response += `\n`;
}
if (sysInfo.cpu) {
const cpu = sysInfo.cpu;
response += `💻 **CPU Information**\n`;
response += `- Model: ${cpu.model}\n`;
response += `- Cores: ${cpu.cores}\n`;
response += `- Speed: ${cpu.speed} MHz\n`;
response += `- Load Average: ${cpu.loadAvg.map(load => load.toFixed(2)).join(', ')}\n`;
// Add enhanced CPU information if available
if (cpu.manufacturer) response += `- Manufacturer: ${cpu.manufacturer}\n`;
if (cpu.brand) response += `- Brand: ${cpu.brand}\n`;
if (cpu.physicalCores) response += `- Physical Cores: ${cpu.physicalCores}\n`;
if (cpu.processors) response += `- Processors: ${cpu.processors}\n`;
if (cpu.socket) response += `- Socket: ${cpu.socket}\n`;
if (cpu.vendor) response += `- Vendor: ${cpu.vendor}\n`;
if (cpu.family) response += `- Family: ${cpu.family}\n`;
if (cpu.stepping) response += `- Stepping: ${cpu.stepping}\n`;
if (cpu.virtualization) response += `- Virtualization: ${cpu.virtualization}\n`;
if (cpu.cache) {
response += `- Cache:\n`;
Object.entries(cpu.cache).forEach(([level, size]) => {
response += ` - ${level}: ${size}\n`;
});
}
if (cpu.temperature) response += `- Temperature: ${cpu.temperature}°C\n`;
if (cpu.currentLoad) response += `- Current Load: ${cpu.currentLoad.toFixed(2)}%\n`;
if (cpu.currentLoadUser) response += `- User Load: ${cpu.currentLoadUser.toFixed(2)}%\n`;
if (cpu.currentLoadSystem) response += `- System Load: ${cpu.currentLoadSystem.toFixed(2)}%\n`;
response += `\n`;
}
if (sysInfo.memory) {
const memory = sysInfo.memory;
response += `🧠 **Memory Information**\n`;
response += `- Total: ${memory.total}\n`;
response += `- Used: ${memory.used} (${memory.usagePercent})\n`;
response += `- Free: ${memory.free}\n`;
// Add enhanced memory information if available
if (memory.active) response += `- Active: ${memory.active}\n`;
if (memory.available) response += `- Available: ${memory.available}\n`;
if (memory.buffers) response += `- Buffers: ${memory.buffers}\n`;
if (memory.cached) response += `- Cached: ${memory.cached}\n`;
if (memory.slab) response += `- Slab: ${memory.slab}\n`;
if (memory.swapTotal) response += `- Swap Total: ${memory.swapTotal}\n`;
if (memory.swapUsed) response += `- Swap Used: ${memory.swapUsed}\n`;
if (memory.swapFree) response += `- Swap Free: ${memory.swapFree}\n`;
// Add memory layout information if available
if (memory.layout && Array.isArray(memory.layout) && memory.layout.length > 0) {
response += `- Memory Modules:\n`;
memory.layout.forEach((module, index) => {
response += ` - Module ${index + 1}:\n`;
if (module.size) response += ` - Size: ${formatBytes(module.size)}\n`;
if (module.bank) response += ` - Bank: ${module.bank}\n`;
if (module.type) response += ` - Type: ${module.type}\n`;
if (module.clockSpeed) response += ` - Clock Speed: ${module.clockSpeed} MHz\n`;
if (module.formFactor) response += ` - Form Factor: ${module.formFactor}\n`;
if (module.manufacturer) response += ` - Manufacturer: ${module.manufacturer}\n`;
if (module.partNum) response += ` - Part Number: ${module.partNum}\n`;
if (module.serialNum) response += ` - Serial Number: ${module.serialNum}\n`;
if (module.voltageConfigured) response += ` - Voltage: ${module.voltageConfigured} V\n`;
});
}
response += `\n`;
}
if (sysInfo.disk) {
response += `💾 **Disk Information**\n`;
// Handle enhanced disk information
if (sysInfo.disk.fsSize && Array.isArray(sysInfo.disk.fsSize)) {
response += `- File Systems:\n`;
sysInfo.disk.fsSize.forEach(fs => {
response += ` - ${fs.fs} (${fs.type}):\n`;
response += ` - Mount: ${fs.mount}\n`;
response += ` - Size: ${fs.size ? formatBytes(fs.size) : 'N/A'}\n`;
response += ` - Used: ${fs.used ? formatBytes(fs.used) : 'N/A'} (${fs.use ? fs.use.toFixed(1) + '%' : 'N/A'})\n`;
response += ` - Available: ${fs.available ? formatBytes(fs.available) : 'N/A'}\n`;
});
} else if (Array.isArray(sysInfo.disk)) {
// Windows format (legacy)
sysInfo.disk.forEach(disk => {
response += `- Drive ${disk.drive}:\n`;
response += ` - Size: ${disk.size}\n`;
response += ` - Used: ${disk.used} (${disk.usagePercent})\n`;
response += ` - Free: ${disk.free}\n`;
});
} else if (sysInfo.disk.error) {
response += `- Error retrieving disk information: ${sysInfo.disk.error}\n`;
} else if (sysInfo.disk.filesystem) {
// Unix format (legacy)
response += `- Filesystem: ${sysInfo.disk.filesystem}\n`;
response += `- Size: ${sysInfo.disk.size}\n`;
response += `- Used: ${sysInfo.disk.used} (${sysInfo.disk.usagePercent})\n`;
response += `- Available: ${sysInfo.disk.available}\n`;
response += `- Mounted on: ${sysInfo.disk.mountedOn}\n`;
}
// Add block devices information if available
if (sysInfo.disk.blockDevices && Array.isArray(sysInfo.disk.blockDevices)) {
response += `- Block Devices:\n`;
sysInfo.disk.blockDevices.forEach(device => {
response += ` - ${device.name}:\n`;
if (device.type) response += ` - Type: ${device.type}\n`;
if (device.size) response += ` - Size: ${formatBytes(device.size)}\n`;
if (device.physical) response += ` - Physical: ${device.physical}\n`;
if (device.uuid) response += ` - UUID: ${device.uuid}\n`;
if (device.label) response += ` - Label: ${device.label}\n`;
if (device.model) response += ` - Model: ${device.model}\n`;
if (device.serial) response += ` - Serial: ${device.serial}\n`;
if (device.removable !== undefined) response += ` - Removable: ${device.removable ? 'Yes' : 'No'}\n`;
if (device.protocol) response += ` - Protocol: ${device.protocol}\n`;
});
}
// Add disk layout information if available
if (sysInfo.disk.diskLayout && Array.isArray(sysInfo.disk.diskLayout)) {
response += `- Disk Layout:\n`;
sysInfo.disk.diskLayout.forEach(disk => {
response += ` - ${disk.device}:\n`;
if (disk.type) response += ` - Type: ${disk.type}\n`;
if (disk.name) response += ` - Name: ${disk.name}\n`;
if (disk.vendor) response += ` - Vendor: ${disk.vendor}\n`;
if (disk.size) response += ` - Size: ${formatBytes(disk.size)}\n`;
if (disk.bytesPerSector) response += ` - Bytes Per Sector: ${disk.bytesPerSector}\n`;
if (disk.totalCylinders) response += ` - Total Cylinders: ${disk.totalCylinders}\n`;
if (disk.totalHeads) response += ` - Total Heads: ${disk.totalHeads}\n`;
if (disk.totalSectors) response += ` - Total Sectors: ${disk.totalSectors}\n`;
if (disk.totalTracks) response += ` - Total Tracks: ${disk.totalTracks}\n`;
if (disk.tracksPerCylinder) response += ` - Tracks Per Cylinder: ${disk.tracksPerCylinder}\n`;
if (disk.sectorsPerTrack) response += ` - Sectors Per Track: ${disk.sectorsPerTrack}\n`;
if (disk.firmwareRevision) response += ` - Firmware Revision: ${disk.firmwareRevision}\n`;
if (disk.serialNum) response += ` - Serial Number: ${disk.serialNum}\n`;
if (disk.interfaceType) response += ` - Interface Type: ${disk.interfaceType}\n`;
});
}
response += `\n`;
}
if (sysInfo.network) {
response += `🌐 **Network Information**\n`;
// Handle enhanced network interfaces information
if (sysInfo.network.interfaces && Array.isArray(sysInfo.network.interfaces)) {
response += `- Interfaces:\n`;
sysInfo.network.interfaces.forEach(iface => {
if (!iface.internal) { // Only show external interfaces
response += ` - ${iface.iface}:\n`;
if (iface.ifaceName) response += ` - Name: ${iface.ifaceName}\n`;
if (iface.ip4) response += ` - IPv4: ${iface.ip4}\n`;
if (iface.ip6) response += ` - IPv6: ${iface.ip6}\n`;
if (iface.mac) response += ` - MAC: ${iface.mac}\n`;
if (iface.speed) response += ` - Speed: ${iface.speed} Mbps\n`;
if (iface.type) response += ` - Type: ${iface.type}\n`;
if (iface.operstate) response += ` - State: ${iface.operstate}\n`;
if (iface.carrier !== undefined) response += ` - Carrier: ${iface.carrier ? 'Yes' : 'No'}\n`;
if (iface.mtu) response += ` - MTU: ${iface.mtu}\n`;
if (iface.dhcp !== undefined) response += ` - DHCP: ${iface.dhcp ? 'Yes' : 'No'}\n`;
}
});
} else if (Array.isArray(sysInfo.network)) {
// Legacy format
sysInfo.network.forEach(net => {
if (!net.internal) { // Only show external interfaces
response += `- Interface: ${net.interface}\n`;
response += ` - IP Address: ${net.address}\n`;
response += ` - Netmask: ${net.netmask}\n`;
response += ` - MAC: ${net.mac}\n`;
}
});
}
// Add network stats if available
if (sysInfo.network.stats && Array.isArray(sysInfo.network.stats)) {
response += `- Network Stats:\n`;
sysInfo.network.stats.forEach(stat => {
if (!stat.iface.includes('lo')) { // Skip loopback
response += ` - ${stat.iface}:\n`;
if (stat.rx_bytes) response += ` - Received: ${formatBytes(stat.rx_bytes)}\n`;
if (stat.tx_bytes) response += ` - Sent: ${formatBytes(stat.tx_bytes)}\n`;
if (stat.rx_errors) response += ` - Receive Errors: ${stat.rx_errors}\n`;
if (stat.tx_errors) response += ` - Send Errors: ${stat.tx_errors}\n`;
if (stat.rx_dropped) response += ` - Receive Dropped: ${stat.rx_dropped}\n`;
if (stat.tx_dropped) response += ` - Send Dropped: ${stat.tx_dropped}\n`;
}
});
}
// Add connection information if available
if (sysInfo.network.connections && sysInfo.network.connections.length > 0) {
const connections = sysInfo.network.connections;
const totalConnections = connections.length;
const establishedCount = connections.filter(conn => conn.state === 'ESTABLISHED').length;
const listeningCount = connections.filter(conn => conn.state === 'LISTEN').length;
response += `- Connections:\n`;
response += ` - Total: ${totalConnections}\n`;
response += ` - Established: ${establishedCount}\n`;
response += ` - Listening: ${listeningCount}\n`;
// Show top 5 connections
if (totalConnections > 0) {
response += ` - Top 5 Connections:\n`;
connections.slice(0, 5).forEach(conn => {
response += ` - ${conn.protocol} ${conn.localAddress}:${conn.localPort} -> ${conn.peerAddress}:${conn.peerPort} (${conn.state})\n`;
});
}
}
// Add wifi networks if available
if (sysInfo.network.wifiNetworks && Array.isArray(sysInfo.network.wifiNetworks)) {
response += `- WiFi Networks:\n`;
sysInfo.network.wifiNetworks.forEach(network => {
response += ` - ${network.ssid}:\n`;
if (network.bssid) response += ` - BSSID: ${network.bssid}\n`;
if (network.mode) response += ` - Mode: ${network.mode}\n`;
if (network.channel) response += ` - Channel: ${network.channel}\n`;
if (network.frequency) response += ` - Frequency: ${network.frequency} MHz\n`;
if (network.signalLevel) response += ` - Signal Level: ${network.signalLevel} dBm\n`;
if (network.quality) response += ` - Quality: ${network.quality}/100\n`;
if (network.security) response += ` - Security: ${network.security.join(', ')}\n`;
});
}
// Add internet connectivity information if available
if (sysInfo.network.internetLatency !== undefined) {
response += `- Internet Connectivity:\n`;
response += ` - Latency: ${sysInfo.network.internetLatency.toFixed(2)} ms\n`;
}
// Add public IP if available
if (sysInfo.network.publicIp) {
response += `- Public IP: ${sysInfo.network.publicIp}\n`;
}
response += `\n`;
}
if (sysInfo.environment) {
response += `🔧 **Environment Variables**\n`;
// Add user information if available
if (sysInfo.environment.user) {
const user = sysInfo.environment.user;
response += `- User Information:\n`;
if (user.username) response += ` - Username: ${user.username}\n`;
if (user.uid) response += ` - UID: ${user.uid}\n`;
if (user.gid) response += ` - GID: ${user.gid}\n`;
if (user.shell) response += ` - Shell: ${user.shell}\n`;
if (user.homedir) response += ` - Home Directory: ${user.homedir}\n`;
}
// Add shell history if available
if (sysInfo.environment.shell && sysInfo.environment.shell.length > 0) {
response += `- Recent Shell Commands:\n`;
sysInfo.environment.shell.slice(0, 5).forEach((cmd, index) => {
response += ` - ${index + 1}: ${cmd}\n`;
});
}
// Add environment variables
if (sysInfo.environment.variables) {
response += `- Environment Variables:\n`;
for (const [key, value] of Object.entries(sysInfo.environment.variables)) {
response += ` - ${key}: ${value}\n`;
}
} else {
// Legacy format
for (const [key, value] of Object.entries(sysInfo.environment)) {
if (typeof value === 'string') {
response += `- ${key}: ${value}\n`;
}
}
}
response += `\n`;
}
if (sysInfo.process) {
response += `⚙️ **Process Information**\n`;
// Add current process information
if (sysInfo.process.current) {
const current = sysInfo.process.current;
response += `- Current Process:\n`;
if (current.pid) response += ` - PID: ${current.pid}\n`;
if (current.ppid) response += ` - Parent PID: ${current.ppid}\n`;
if (current.name) response += ` - Name: ${current.name}\n`;
if (current.cpu) response += ` - CPU Usage: ${current.cpu.toFixed(2)}%\n`;
if (current.memory) response += ` - Memory Usage: ${formatBytes(current.memory)}\n`;
if (current.started) response += ` - Started: ${new Date(current.started).toLocaleString()}\n`;
if (current.state) response += ` - State: ${current.state}\n`;
if (current.path) response += ` - Path: ${current.path}\n`;
if (current.command) response += ` - Command: ${current.command}\n`;
if (current.params) response += ` - Parameters: ${current.params.join(' ')}\n`;
} else {
// Legacy format
response += `- PID: ${sysInfo.process.pid}\n`;
response += `- Node.js Version: ${sysInfo.process.version}\n`;
response += `- Current Directory: ${sysInfo.process.cwd}\n`;
response += `- Memory Usage: ${Math.round(sysInfo.process.memoryUsage.rss / (1024 * 1024))} MB\n`;
}
// Add process summary if available
if (sysInfo.process.summary) {
const summary = sysInfo.process.summary;
response += `- Process Summary:\n`;
if (summary.total) response += ` - Total: ${summary.total}\n`;
if (summary.running) response += ` - Running: ${summary.running}\n`;
if (summary.blocked) response += ` - Blocked: ${summary.blocked}\n`;
if (summary.sleeping) response += ` - Sleeping: ${summary.sleeping}\n`;
if (summary.unknown) response += ` - Unknown: ${summary.unknown}\n`;
}
// Add top processes if available
if (sysInfo.process.list && Array.isArray(sysInfo.process.list)) {
response += `- Top Processes (by CPU):\n`;
sysInfo.process.list.slice(0, 10).forEach((proc, index) => {
response += ` - ${index + 1}: ${proc.name} (PID: ${proc.pid})\n`;
response += ` - CPU: ${proc.cpu.toFixed(2)}%, Memory: ${formatBytes(proc.mem)}\n`;
});
}
// Add services if available
if (sysInfo.process.services && Array.isArray(sysInfo.process.services)) {
response += `- System Services:\n`;
sysInfo.process.services.slice(0, 10).forEach((service, index) => {
response += ` - ${index + 1}: ${service.name} (${service.running ? 'Running' : 'Stopped'})\n`;
if (service.pids && service.pids.length > 0) {
response += ` - PIDs: ${service.pids.join(', ')}\n`;
}
if (service.startmode) response += ` - Start Mode: ${service.startmode}\n`;
});
}
response += `\n`;
}
return response;
}
async function processWithAI(prompt, context = '') {
try {
// Check if the prompt is related to system information
if (isSystemInfoQuery(prompt)) {
try {
// First get basic system info to provide context
const basicInfo = await getSystemInfo('basic');
// Use AI to determine what system information is being requested
const aiResponse = await determineSystemInfoQuery(prompt, basicInfo);
// Get the specific system information based on AI's determination
const systemInfo = await getSystemInfo(aiResponse.query);
return formatSystemInfoResponse(systemInfo, prompt);
} catch (sysError) {
console.error('❌ System info error:', sysError.message);
// If system info fails, fall back to AI processing
}
}
// Regular AI processing
const models = ['kimi', 'mvrk', 'gma3', 'dsv3', 'qw32b', 'ms24b', 'll70b', 'qw3', 'mp4', 'nlm3'];
const modelRequests = models.map(model =>
fetch('https://traceai.dukeindustries7.workers.dev/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: encryptData({
a: model,
q: prompt,
r: [],
i: [],
c: context
})
})
.then(res => res.text())
.then(decryptData)
);
const responses = await Promise.all(modelRequests);
const responseTexts = responses.map(r => r.text);
const finalResponse = await fetch('https://traceai.dukeindustries7.workers.dev/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: encryptData({
a: 'gfinal',
q: prompt,
r: responseTexts.filter(text => text && typeof text === 'string'),
i: [],
c: context
})
});
const encryptedResult = await finalResponse.text();
const decryptedResult = decryptData(encryptedResult);
return decryptedResult.text || 'No response generated';
} catch (error) {
console.error('❌ Processing error:', error.message);
throw error;
}
}
module.exports = {
processWithAI,
determineSystemInfoQuery,
isSystemInfoQuery,
formatSystemInfoResponse
};