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

268 lines (267 loc) 11.2 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.hasError = exports.ERROR_BOL = exports.ERRORFILE_PATH = exports.LOGFILE_PATH = exports.LOG_DIR = void 0; exports.read_file = read_file; exports.write_file = write_file; exports.update_file = update_file; exports.run_shell = run_shell; exports.browse_url = browse_url; exports.task_completed = task_completed; const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const cheerio = __importStar(require("cheerio")); const execa_1 = __importDefault(require("execa")); const turndown_1 = __importDefault(require("turndown")); const constants_1 = require("../constants"); const sectionUpdate_1 = require("../utils/sectionUpdate"); const ignore_1 = require("../utils/ignore"); const logger_1 = __importDefault(require("../utils/logger")); const remoteExecutor_1 = require("../remoteExecution/remoteExecutor"); const windowsHelper_1 = require("../remoteExecution/windowsHelper"); exports.LOG_DIR = path_1.default.join(constants_1.CONFIG_DIR, 'logs'); exports.LOGFILE_PATH = path_1.default.join(exports.LOG_DIR, 'commands.log'); exports.ERRORFILE_PATH = path_1.default.join(exports.LOG_DIR, 'errors.log'); function read_file(args) { try { if (remoteExecutor_1.RemoteExecutor.instance.isEnabled()) { return null; } const data = fs_1.default.readFileSync(args.path, 'utf8'); return data; } catch (error) { logger_1.default.error('Error reading file:', error); return null; } } function write_file(args) { return __awaiter(this, void 0, void 0, function* () { if (remoteExecutor_1.RemoteExecutor.instance.isEnabled()) { const escapedContent = args.content.replace(/"/g, '\\"'); const config = remoteExecutor_1.RemoteExecutor.instance.getConfig(); try { if (config.type === 'winrm') { const result = yield remoteExecutor_1.RemoteExecutor.instance.executeCommand(`powershell Write-Host ${escapedContent || ''} -NoNewline > "${args.path}"`); if ((0, windowsHelper_1.isCommandNotFound)(result)) { throw new Error(`Failed to write file: '${result}'`); } } else { try { yield remoteExecutor_1.RemoteExecutor.instance.executeCommand(`tee "${args.path}"`, escapedContent); } catch (error) { if (error.message.includes('Permission denied')) { yield run_shell({ command: `echo "${escapedContent}" | sudo tee "${args.path}" > /dev/null`, }); } else { throw error; } } } } catch (error) { throw new Error(`Failed to write file: ${error}`); } return ` File written: ${args.path} ${escapedContent}`; } logger_1.default.debug(`Writing file at "${args.path}"`); try { fs_1.default.mkdirSync(path_1.default.dirname(args.path), { recursive: true }); fs_1.default.writeFileSync(args.path, args.content); } catch (error) { if (error.code === 'EACCES') { try { const escapedContent = args.content.replace(/"/g, '\\"'); yield run_shell({ command: `echo "${escapedContent}" | sudo tee "${args.path}" > /dev/null`, }); } catch (e) { throw new Error(`Failed to write file with sudo: ${e}`); } } else { throw error; } } const ignoreManager = ignore_1.IgnoreManager.getInstance(); const content = ignoreManager.isIgnored(args.path) ? '' : `Content : ${args.content}`; return ` File written: ${args.path} ${content}`; }); } function update_file(_a) { return __awaiter(this, arguments, void 0, function* ({ sectionsDiff, path, }) { logger_1.default.debug('Updating sections:', sectionsDiff); try { const fileContent = remoteExecutor_1.RemoteExecutor.instance.isEnabled() ? yield remoteExecutor_1.RemoteExecutor.instance.executeCommand(`cat "${path}"`) : fs_1.default.readFileSync(path, 'utf8'); const newContent = (0, sectionUpdate_1.modifyCodeSections)({ originalContent: fileContent, diffSections: sectionsDiff, }); if (remoteExecutor_1.RemoteExecutor.instance.isEnabled()) { yield write_file({ path, content: newContent }); } else { try { fs_1.default.writeFileSync(path, newContent); } catch (error) { if (error.code === 'EACCES') { try { const escapedContent = newContent.replace(/"/g, '\\"'); yield run_shell({ command: `echo "${escapedContent}" | sudo tee "${path}" > /dev/null`, }); } catch (e) { throw new Error(`Failed to write file with sudo: ${e}`); } } else { throw error; } } } const ignoreManager = ignore_1.IgnoreManager.getInstance(); const content = ignoreManager.isIgnored(path) ? '' : `New file Content : \`\`\` ${newContent} \`\`\``; return ` File updated: ${path} ${content}`; } catch (error) { return `${exports.ERROR_BOL} I failed to run update_file on ${path}, please fix the situation, errors below.\n ${error.message} ${error}`; } }); } function logExecution(result) { fs_1.default.mkdirSync(exports.LOG_DIR, { recursive: true }); fs_1.default.appendFileSync(exports.LOGFILE_PATH, result + '\n'); } function run_shell(_a) { return __awaiter(this, arguments, void 0, function* ({ command, shell, env, }) { logger_1.default.debug(`Running shell command: ${command}`); if (remoteExecutor_1.RemoteExecutor.instance.isEnabled()) { try { const config = remoteExecutor_1.RemoteExecutor.instance.getConfig(); const rawCmd = config.raw_ssh || false; logger_1.default.debug('Raw SSH:', rawCmd); const result = yield remoteExecutor_1.RemoteExecutor.instance.executeCommand(command, undefined, rawCmd); logExecution(result); return result; } catch (error) { logger_1.default.error('Remote execution failed:', error); return `${exports.ERROR_BOL} I failed to run ${command}, please fix the situation, errors below.\n ${error.message} ${error}`; } } try { const { stderr, stdout } = yield (0, execa_1.default)(command, { shell: shell || true, preferLocal: true, env, }); let output = ''; if (stdout) output += stdout; if (stderr) output += stderr; logExecution(output); return output; } catch (error) { return `${exports.ERROR_BOL} I failed to run ${command}, please fix the situation, errors below.\n ${error.message} ${error}`; } }); } exports.ERROR_BOL = `ERROR :`; const hasError = (output) => { return output.startsWith(exports.ERROR_BOL); }; exports.hasError = hasError; function browse_url(args) { return __awaiter(this, void 0, void 0, function* () { const html = yield fetch(args.url).then((res) => res.text()); const $ = cheerio.load(html); $('script').remove(); $('style').remove(); $('iframe, img, video, object').remove(); const text = $('body').text(); const turndownService = new turndown_1.default(); const md = turndownService.turndown(text); return ` Result of content of page : ${md.replace(/\s+/g, '')} `; }); } function task_completed(args) { return __awaiter(this, void 0, void 0, function* () { return (args === null || args === void 0 ? void 0 : args.summary) || (args === null || args === void 0 ? void 0 : args.output) || 'Task completed!'; }); }