UNPKG

rosie-cli

Version:

AI-powered command-line interface tool that uses OpenAI's API to help you interact with your computer through natural language

233 lines (230 loc) 11.9 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); 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.getLastBashCommand = exports.memoryStore = void 0; exports.showPopupDialog = showPopupDialog; const chatgpt_1 = require("../lib/chatgpt"); const everything_1 = require("../lib/everything"); const filestore_1 = require("../lib/filestore"); const child_process_1 = require("child_process"); const readline = __importStar(require("readline")); const path_1 = __importDefault(require("path")); const os_1 = __importDefault(require("os")); const uuid_1 = require("uuid"); const configManager_1 = require("../configManager"); const fs_1 = __importDefault(require("fs")); const promises_1 = __importDefault(require("fs/promises")); const screenshot_1 = require("../lib/screenshot/screenshot"); exports.memoryStore = new filestore_1.FileStore(path_1.default.join(os_1.default.homedir(), '.rosie-memory.json'), { items: [] }); const configManager = new configManager_1.ConfigManager(); class MainProcessingService { processMessage(message, context) { return __awaiter(this, void 0, void 0, function* () { // Process the incoming message using ChatGPT directl const response = yield (0, chatgpt_1.getChatGPTResponse)(message.text, context, { thinking: context.params.thinking }); const answer = { text: response.text, ts: Date.now() }; const action = { type: "produce_text", params: { inputMessage: message, mode: context.params.mode }, result: response.text }; let update = { answer, actions: [action], actionRequests: response.actionRequests }; context.update(update); if (response.actionRequests && response.actionRequests.length > 0) { // Execute the actions for (const action of response.actionRequests) { if (action.type === "search_pc") { // Search the pc for the query const results = yield (0, everything_1.searchEverything)(action.params.query); const searchAnalysis = yield (0, chatgpt_1.getChatGPTResponse)(`The results of the search are as follows: ${JSON.stringify(results)} Please analyze the results and provide a detailed analysis of the results based on the original query. You can not call any additional actions for this query. `, context, { role: "system", dontUpdateHistory: true }); action.result = searchAnalysis.text; } else if (action.type === "add_memory") { // Add a memory about the user const memory = yield exports.memoryStore.load(); memory.items.push({ text: action.params.text, date: Date.now() }); yield exports.memoryStore.save(memory); action.result = true; } else if (action.type === "run_cmd") { // Run a command on the pc const cmd = action.params.cmd; try { const { stdout, stderr } = yield new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { const confirmed = yield showPopupDialog("Confirm Command", `Run command: ${cmd}`); if (!confirmed) { resolve({ stdout: "", stderr: "User canceled the action" }); return; } (0, child_process_1.exec)(cmd, (error, stdout, stderr) => { if (error) { resolve({ stdout, stderr: error.message }); } else { resolve({ stdout, stderr }); } }); })); action.result = stdout || stderr; } catch (error) { action.result = error.message; } } else if (action.type === "new_conversation") { // Create a new conversation const newId = action.params.name || (0, uuid_1.v4)(); yield chatgpt_1.chatHistories.save({ [newId]: yield (0, chatgpt_1.getOrCreateChatHistory)(newId) }); configManager.setActiveConversationId(newId); action.result = true; const newUpdate = { answer: { text: "New conversation started", ts: Date.now() }, actions: [], actionRequests: [] }; return newUpdate; } else if (action.type === "set_conversation") { // Set the conversation configManager.setActiveConversationId(action.params.id); action.result = true; const newUpdate = { answer: { text: "Conversation set to " + action.params.id, ts: Date.now() }, actions: [], actionRequests: [] }; return newUpdate; } else if (action.type === "gen_image") { // Generate an image const image = yield (0, chatgpt_1.generateImage)(action.params.prompt, action.params.inputImages, context); // Save the base64 image to a file and open it with native image viewer const tempDir = os_1.default.tmpdir(); const imagePath = path_1.default.join(tempDir, `rosie-image-${Date.now()}.png`); try { // Convert base64 to buffer and save to file const imageBuffer = Buffer.from(image, 'base64'); yield promises_1.default.writeFile(imagePath, imageBuffer); // Open the image with the default image viewer const openCommand = process.platform === 'win32' ? `start "" "${imagePath}"` : process.platform === 'darwin' ? `open "${imagePath}"` : `xdg-open "${imagePath}"`; (0, child_process_1.exec)(openCommand, (error) => { if (error) { console.error('Error opening image:', error); } }); } catch (error) { console.error('Error saving or opening image:', error); } action.result = "Image generated successfully. Path: " + imagePath; } else if (action.type === "analyze_screen") { // Analyze the screen const screenshot = yield (0, screenshot_1.getScreenshots)(); const result = yield (0, chatgpt_1.analyzeImage)(screenshot[action.params.screenIndex].buffer, action.params.prompt, context); action.result = result; } } const newResponse = yield (0, chatgpt_1.getChatGPTResponse)(` You have performed the following actions: ${JSON.stringify(response.actionRequests)} Based on the results, formulate a final answer to the user's query. You can not call any additional actions for this query. `, context, { thinking: false, role: "system" }); const newUpdate = { answer: { text: newResponse.text, ts: Date.now() }, actions: [], actionRequests: [] }; return newUpdate; } else { return update; } }); } } exports.default = MainProcessingService; const getLastBashCommand = () => { try { const homedir = require('os').homedir(); const bashHistoryPath = path_1.default.join(homedir, '.bash_history'); if (fs_1.default.existsSync(bashHistoryPath)) { const history = fs_1.default.readFileSync(bashHistoryPath, 'utf-8'); const commands = history.split('\n').filter(cmd => cmd.trim() !== ''); if (commands.length > 0) { const lastCommand = commands[commands.length - 1]; return lastCommand; } else { return null; } } else { } } catch (error) { } }; exports.getLastBashCommand = getLastBashCommand; function showPopupDialog(title, message) { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); return new Promise((resolve) => { console.log(`\n${title}`); console.log(`${message}`); rl.question('Confirm? (y/n): ', (answer) => { rl.close(); resolve(answer.toLowerCase() === 'y'); }); }); }