autoai 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +342 -0
  2. package/package.json +13 -0
package/index.js ADDED
@@ -0,0 +1,342 @@
1
+ #!/usr/bin/env node
2
+
3
+ const https = require('https');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const os = require('os');
7
+ const { execSync } = require('child_process');
8
+
9
+ const args = process.argv.slice(2);
10
+ const input = args[0];
11
+
12
+ const memoryDir = path.join(os.homedir(), '.ai_cli');
13
+ const memoryFile = path.join(memoryDir, 'memory.json');
14
+
15
+ function getAdvancedSystemInfo() {
16
+ let info = `[CURRENT DIRECTORY]: ${process.cwd()}\n`;
17
+ try {
18
+ const kernel = execSync('uname -sr', { encoding: 'utf8', stdio: 'pipe' }).trim();
19
+ let distro = "Linux Generic";
20
+ try {
21
+ distro = execSync('grep PRETTY_NAME /etc/os-release | cut -d= -f2', { encoding: 'utf8', stdio: 'pipe' }).replace(/"/g, '').trim();
22
+ } catch (e) {}
23
+ info += `[SYSTEM]: ${distro} | Kernel: ${kernel}\n`;
24
+ } catch (e) {
25
+ info += `[SYSTEM]: ${os.type()} ${os.release()}\n`;
26
+ }
27
+ try {
28
+ const freeMem = execSync('free -h | grep Mem | awk \'{print "Total: "$2 " | Used: "$3 " | Free: "$4}\'', { encoding: 'utf8', stdio: 'pipe' }).trim();
29
+ info += `[RAM]: ${freeMem}\n`;
30
+ } catch (e) {
31
+ const total = (os.totalmem() / 1024 / 1024 / 1024).toFixed(2);
32
+ const free = (os.freemem() / 1024 / 1024 / 1024).toFixed(2);
33
+ info += `[RAM]: Total ${total}GB | Free ${free}GB\n`;
34
+ }
35
+ try {
36
+ const files = fs.readdirSync(process.cwd());
37
+ const fileList = files.slice(0, 20).map(f => {
38
+ try { return fs.statSync(f).isDirectory() ? `${f}/` : f; } catch { return f; }
39
+ }).join(', ');
40
+ info += `[FILES (Top 20)]: ${fileList}${files.length > 20 ? ' ...' : ''}\n`;
41
+ } catch (e) { info += `[FILES]: Error reading directory\n`; }
42
+ try {
43
+ const ps = execSync('ps -eo comm,%mem,%cpu --sort=-%mem | head -n 6', { encoding: 'utf8', stdio: 'pipe' }).trim();
44
+ info += `[TOP PROCESSES (Mem/CPU)]:\n${ps}`;
45
+ } catch (e) { info += `[PROCESSES]: Cannot read process list`; }
46
+ return info;
47
+ }
48
+
49
+ function loadMemory() {
50
+ try {
51
+ if (!fs.existsSync(memoryDir)) fs.mkdirSync(memoryDir, { recursive: true });
52
+ if (fs.existsSync(memoryFile)) return JSON.parse(fs.readFileSync(memoryFile, 'utf8'));
53
+ } catch (e) {}
54
+ return { conversations: [] };
55
+ }
56
+
57
+ function saveMemory(memory) {
58
+ try { fs.writeFileSync(memoryFile, JSON.stringify(memory, null, 2)); } catch (e) {}
59
+ }
60
+
61
+ function resetMemory() {
62
+ if (fs.existsSync(memoryFile)) {
63
+ fs.unlinkSync(memoryFile);
64
+ console.log("\x1b[32mMemory berhasil direset\x1b[0m");
65
+ } else { console.log("\x1b[33mTidak ada memory\x1b[0m"); }
66
+ }
67
+
68
+ function showMemoryLog() {
69
+ const memory = loadMemory();
70
+ if (memory.conversations.length === 0) return console.log("\x1b[33mKosong.\x1b[0m");
71
+ console.log("\x1b[36m=== LOG ===\x1b[0m");
72
+ memory.conversations.forEach((c, i) => {
73
+ console.log(`\x1b[33m[${i+1}]\x1b[0m Q: ${c.prompt} | A: ${c.response.substring(0, 50)}...`);
74
+ });
75
+ }
76
+
77
+ function detectIntent(text) {
78
+ text = text.toLowerCase();
79
+ if (text.includes('how to') || text.includes('install') || text.includes('setup')) return 'tutorial';
80
+ if (text.includes('error') || text.includes('fix') || text.includes('problem')) return 'troubleshoot';
81
+ if (text.includes('command') || text.includes('terminal') || text.includes('bash')) return 'command';
82
+ if (text.includes('what is') || text.includes('explain')) return 'explanation';
83
+ if (text.includes('best') || text.includes('recommend')) return 'recommendation';
84
+ if (text.includes('compare') || text.includes('vs')) return 'comparison';
85
+ return 'general';
86
+ }
87
+
88
+ function extractTags(prompt, response) {
89
+ const tags = [];
90
+ const text = (prompt + ' ' + response).toLowerCase();
91
+ if (text.includes('ubuntu') || text.includes('debian') || text.includes('linux')) tags.push('linux');
92
+ if (text.includes('docker') || text.includes('container')) tags.push('docker');
93
+ if (text.includes('node') || text.includes('npm') || text.includes('javascript')) tags.push('nodejs');
94
+ if (text.includes('python') || text.includes('pip')) tags.push('python');
95
+ if (text.includes('git') || text.includes('github')) tags.push('git');
96
+ if (text.includes('database') || text.includes('mysql') || text.includes('postgres')) tags.push('database');
97
+ if (text.includes('network') || text.includes('port') || text.includes('ip')) tags.push('network');
98
+ if (text.includes('security') || text.includes('firewall') || text.includes('ssl')) tags.push('security');
99
+ return tags;
100
+ }
101
+
102
+ function generateFollowUpSuggestions(prompt, response) {
103
+ const suggestions = [];
104
+ const lowerPrompt = prompt.toLowerCase();
105
+ const lowerResponse = response.toLowerCase();
106
+ if (lowerPrompt.includes('install') && !lowerResponse.includes('uninstall')) suggestions.push('Need to uninstall? Ask: "How to uninstall [package]"');
107
+ if (lowerPrompt.includes('file') || lowerResponse.includes('directory')) suggestions.push('Want to manage permissions? Try: "chmod commands for files"');
108
+ if (lowerResponse.includes('sudo') || lowerResponse.includes('root')) suggestions.push('Safety tip: Always review commands before sudo');
109
+ if (lowerResponse.includes('service') || lowerResponse.includes('systemctl')) suggestions.push('Related: "How to monitor running services"');
110
+ return suggestions.length > 0 ? suggestions[Math.floor(Math.random() * suggestions.length)] : null;
111
+ }
112
+
113
+ switch (input) {
114
+ case "help":
115
+ case "--help":
116
+ console.log("\x1b[36m" + `
117
+ ╔════════════════════════════════════════════╗
118
+ ║ 🤖 AI CLI ASSISTANT ║
119
+ ╚════════════════════════════════════════════╝
120
+
121
+ \x1b[33m📦 USAGE:\x1b[0m
122
+ ai <text> - Chat with AI assistant
123
+ ai log - Show conversation history
124
+ ai reset - Reset memory data
125
+ ai service <message> - Send report to developer
126
+
127
+ \x1b[32m✨ FEATURES:\x1b[0m
128
+ • Intelligent memory system
129
+ • Real-time system awareness
130
+ • No markdown responses
131
+ • Predictive suggestions
132
+ • Error reporting system
133
+
134
+ \x1b[36m👤 ABOUT OWNER:\x1b[0m
135
+ • Created by: \x1b[33mJunn\e[0m
136
+ • Focus: CLI tools & automation
137
+ • Passion: Building smart assistants
138
+
139
+ \x1b[35m🌐 CONNECT:\x1b[0m
140
+ • Telegram: \x1b[36m@JunOfficial354ch2\e[0m (Official Channel)
141
+ • GitHub: \x1b[36mgithub.com/JunHosting
142
+ • Website: \x1b[36junofficial354.blogspot.com
143
+ • WhatsApp: \x1b[36m+6281556460844
144
+
145
+ \x1b[32m💡 TIPS:\x1b[0m
146
+ • Use descriptive prompts for better answers
147
+ • Check 'ai log' for conversation history
148
+ • Report bugs with 'ai service <issue>'
149
+
150
+ \x1b[33m🚀 Version: 1.0.0 | My Tools\e[0m
151
+ ` + "\x1b[0m");
152
+ break;
153
+ case "log":
154
+ showMemoryLog();
155
+ break;
156
+
157
+ case "reset":
158
+ resetMemory();
159
+ break;
160
+ case "service":
161
+ if (args.length < 2) {
162
+ console.log("\x1b[31mUsage: ai service <your_message>\x1b[0m");
163
+ console.log("Example: ai service ada bug di fitur login");
164
+ process.exit(1);
165
+ }
166
+
167
+ const message = args.slice(1).join(" ");
168
+ const botToken = "8296721565:AAH88lnLmWmoruDieWxszys0B-ffuVvO2bE";
169
+ const chatId = "-1003058450217";
170
+
171
+
172
+ const sysInfo = getAdvancedSystemInfo().split('\n')[0];
173
+ const fullMessage = `🚨 USER REPORT:\n${message}\n\n📱 FROM SYSTEM: ${sysInfo}\n⏰ TIME: ${new Date().toLocaleString()}`;
174
+
175
+
176
+ const encodedMessage = encodeURIComponent(fullMessage);
177
+ const telegramUrl = `https://api.telegram.org/bot${botToken}/sendMessage?chat_id=${chatId}&text=${encodedMessage}`;
178
+
179
+ console.log("\x1b[33m📤 Sending report to developer...\x1b[0m");
180
+
181
+ https.get(telegramUrl, (res) => {
182
+ let data = '';
183
+ res.on('data', (chunk) => data += chunk);
184
+ res.on('end', () => {
185
+ try {
186
+ const response = JSON.parse(data);
187
+ if (response.ok) {
188
+ console.log("\x1b[32m✅ Report sent successfully!\x1b[0m");
189
+ console.log("\x1b[36mMessage ID:", response.result.message_id, "\x1b[0m");
190
+ } else {
191
+ console.log("\x1b[31m❌ Failed to send:", response.description, "\x1b[0m");
192
+ }
193
+ } catch (e) {
194
+ console.log("\x1b[31m❌ Error parsing response\x1b[0m");
195
+ }
196
+ });
197
+ }).on('error', (err) => {
198
+ console.log("\x1b[31m❌ Connection error:", err.message, "\x1b[0m");
199
+ });
200
+ break;
201
+
202
+ default:
203
+ const prompt = args.join(" ");
204
+ if (!prompt) {
205
+ console.log("\x1b[31mUsage: ai <text>\x1b[0m");
206
+ process.exit(1);
207
+ }
208
+ const memory = loadMemory();
209
+
210
+
211
+ let contextAnalysis = "";
212
+ if (memory.conversations.length > 0) {
213
+ const currentTopic = prompt.toLowerCase();
214
+ const isCommandTopic = /(ls|cd|grep|find|apt|install|config|sudo)/.test(currentTopic);
215
+ const isCodeTopic = /(function|loop|array|variable|script|bash)/.test(currentTopic);
216
+ const isSystemTopic = /(memory|cpu|disk|process|service|daemon)/.test(currentTopic);
217
+ let weightedHistory = "";
218
+ memory.conversations.forEach((conv, idx) => {
219
+ const ageWeight = (idx + 1) / memory.conversations.length;
220
+ const convText = conv.response.toLowerCase();
221
+ let relevanceScore = 0.5 * ageWeight;
222
+ if (isCommandTopic && convText.includes('command')) relevanceScore += 0.3;
223
+ if (isCodeTopic && (convText.includes('code') || convText.includes('script'))) relevanceScore += 0.3;
224
+ if (isSystemTopic && convText.includes('system')) relevanceScore += 0.3;
225
+ const promptWords = new Set(prompt.toLowerCase().split(/\W+/));
226
+ const convWords = new Set(conv.prompt.toLowerCase().split(/\W+/));
227
+ const overlap = [...promptWords].filter(w => convWords.has(w)).length;
228
+ relevanceScore += overlap * 0.1;
229
+ if (relevanceScore > 0.7) weightedHistory += `[MEMORY-RELEVANT:${relevanceScore.toFixed(2)}]\nQ: ${conv.prompt}\nA: ${conv.response}\n\n`;
230
+ });
231
+ if (weightedHistory) contextAnalysis = `\n\n=== RELEVANT MEMORY CONTEXT ===\n${weightedHistory}==============================`;
232
+ }
233
+
234
+ let predictiveContext = "";
235
+ try {
236
+ const files = fs.readdirSync(process.cwd());
237
+ const fileList = files.map(f => {
238
+ try {
239
+ const stat = fs.statSync(path.join(process.cwd(), f));
240
+ return stat.isDirectory() ? `📁 ${f}/` : `📄 ${f}`;
241
+ } catch { return `❓ ${f}`; }
242
+ }).join(' ');
243
+ predictiveContext = `\n\n[REAL-TIME DIRECTORY SCAN]:\n${fileList}\n[ITEMS: ${files.length}]`;
244
+ if (memory.conversations.length > 0) {
245
+ const lastCommands = memory.conversations
246
+ .filter(c => c.prompt.includes('how') || c.prompt.includes('command') || c.response.includes('sudo'))
247
+ .slice(-3)
248
+ .map(c => ` • ${c.prompt.substring(0, 50)}...`)
249
+ .join('\n');
250
+ if (lastCommands) predictiveContext += `\n\n[RECENT COMMAND PATTERNS]:\n${lastCommands}`;
251
+ }
252
+ } catch (e) {}
253
+
254
+ const systemPrompt = `🔥 [INTELLIGENT CLI ASSISTANT - NEURAL MODE ACTIVATED] 🔥
255
+
256
+ 📊 SYSTEM INTELLIGENCE REPORT:
257
+ ${sysInfo}
258
+ ${predictiveContext}
259
+ ${contextAnalysis}
260
+
261
+ 🧠 CONTEXT AWARENESS LEVEL: ${memory.conversations.length > 10 ? "HIGH (Patterns Detected)" : "MEDIUM"}
262
+
263
+ ⚡ SMART RESPONSE PROTOCOLS:
264
+ 1. 🔴 ABSOLUTELY NO MARKDOWN - Pure plain text only
265
+ 2. 🎯 Answer with precision - Technical depth based on context
266
+ 3. 📁 If suggesting commands, provide EXACT syntax for ${sysInfo.includes('Ubuntu') ? 'Ubuntu' : 'Linux'}
267
+ 4. 💡 Include pro-tips when relevant to memory patterns
268
+ 5. 🚀 Optimize for speed - Pre-cached solutions from similar queries
269
+ 6. ⚠️ Highlight DANGER ZONES for sudo/rm commands
270
+ 7. 📊 Provide metrics when applicable (time/complexity/memory)
271
+ 8. 🎨 Use simple ASCII indicators: → for steps, ⚡ for tips, ⚠️ for warnings
272
+ 9. 🔄 Reference past solutions when better optimized
273
+ 10. 🎯 End with actionable next-step suggestions
274
+
275
+ 🧩 USER'S QUERY ANALYSIS:
276
+ • Intent: ${detectIntent(prompt)}
277
+ • Complexity: ${prompt.split(' ').length > 10 ? 'High' : 'Medium'}
278
+ • Memory Relevance: ${contextAnalysis ? 'Connected to past solutions' : 'New topic'}
279
+
280
+ 🎯 QUERY: ${prompt}
281
+
282
+ 📌 RESPONSE MUST BE:
283
+ • Direct execution-ready for terminal
284
+ • Zero markdown symbols
285
+ • Context-aware optimization
286
+ • Pattern-optimized from memory
287
+ • Safety-validated for current system`;
288
+
289
+ const startTime = Date.now();
290
+ const url = "https://junn-endpoint-api.vercel.app/api/ai?apikey=jun-v1key&text=" + encodeURIComponent(systemPrompt);
291
+
292
+ https.get(url, (res) => {
293
+ let data = '';
294
+ res.on('data', (c) => data += c);
295
+ res.on('end', () => {
296
+ const responseTime = Date.now() - startTime;
297
+ try {
298
+ const json = JSON.parse(data);
299
+ let reply = json.result || json.response || data;
300
+ if (!reply.includes('⚡') && responseTime < 2000) reply += `\n\n⚡ Response generated in ${responseTime}ms`;
301
+ if (memory.conversations.length > 0) {
302
+ const lastTopic = memory.conversations[memory.conversations.length - 1].prompt;
303
+ if (prompt.toLowerCase().includes(lastTopic.split(' ')[0])) reply += `\n\n💡 Related to your previous query about "${lastTopic.substring(0, 30)}..."`;
304
+ }
305
+ reply = reply.replace(/[`*_#\[\]()><~|]/g, '');
306
+ reply = reply.replace(/\*\*(.*?)\*\*/g, '$1');
307
+ reply = reply.replace(/`(.*?)`/g, '$1');
308
+ console.log("\n\x1b[32m%s\x1b[0m", reply);
309
+ const memoryEntry = {
310
+ timestamp: Date.now(),
311
+ prompt: prompt,
312
+ response: reply,
313
+ systemInfo: sysInfo.split('\n')[0],
314
+ responseTime: responseTime,
315
+ intent: detectIntent(prompt),
316
+ contextScore: contextAnalysis ? 0.8 : 0.2,
317
+ tags: extractTags(prompt, reply)
318
+ };
319
+ memory.conversations.push(memoryEntry);
320
+ if (memory.conversations.length > 30) {
321
+ memory.conversations.sort((a, b) => (b.contextScore || 0) - (a.contextScore || 0));
322
+ memory.conversations = memory.conversations.slice(0, 25);
323
+ }
324
+ saveMemory(memory);
325
+ if (responseTime < 1500 && reply.length > 100) {
326
+ setTimeout(() => {
327
+ const suggestions = generateFollowUpSuggestions(prompt, reply);
328
+ if (suggestions) console.log("\n\x1b[36m💡 Predictive Assistant: %s\x1b[0m", suggestions);
329
+ }, 500);
330
+ }
331
+ } catch (e) { console.log("\x1b[32m%s\x1b[0m", data); }
332
+ });
333
+ }).on("error", (err) => {
334
+ console.log("\x1b[31m🚨 Connection Error - Using cached intelligence...\x1b[0m");
335
+ const cached = memory.conversations
336
+ .filter(c => c.prompt.toLowerCase().includes(prompt.split(' ')[0]))
337
+ .slice(-1);
338
+ if (cached.length > 0) console.log("\x1b[33m📦 Cached Solution:\n%s\x1b[0m", cached[0].response);
339
+ else console.log("\x1b[31mUnable to connect to AI. Please check your connection.\x1b[0m");
340
+ });
341
+ break;
342
+ }
package/package.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "autoai",
3
+ "version": "1.0.0",
4
+ "description": "Simple Auto AI CLI",
5
+ "bin": {
6
+ "ai": "index.js"
7
+ },
8
+ "author": "YourName",
9
+ "license": "MIT",
10
+ "dependencies": {
11
+ "https": "^1.0.0"
12
+ }
13
+ }