@personnn/personnnkit
Version:
🇵 PersonnnKit - El Agente Kit Universal. Framework revolucionario para crear agentes de IA con HTML + Python. Simplicidad radical vs frameworks gigantes.
366 lines (341 loc) • 12.5 kB
JavaScript
"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;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.TemplateCompiler = void 0;
exports.compileAgent = compileAgent;
exports.listAvailableAgents = listAvailableAgents;
exports.getAgentInfo = getAgentInfo;
const index_1 = require("./agents/index");
const config_1 = require("./config");
const styles_1 = require("./styles");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const child_process_1 = require("child_process");
class TemplateCompiler {
constructor() {
this.baseFiles = {
'public/css/tailwind.css': styles_1.tailwindCssTemplate,
'personnn.config.js': config_1.configTemplate,
'package.json': this.generatePackageJson(),
'runtime/dev-server.js': this.generateDevServer(),
'runtime/api.js': this.generateApiServer(),
'scripts/install-python.sh': this.generatePythonInstaller(),
'.gitignore': this.generateGitignore()
};
}
async compile(options) {
const agent = index_1.availableAgents.find(a => a.id === options.agentId);
if (!agent) {
throw new Error(`Agente '${options.agentId}' no encontrado`);
}
console.log(`🔨 Compilando agente: ${agent.name}`);
// Crear directorio de salida
this.ensureDirectory(options.outputDir);
// Copiar archivos base
this.copyBaseFiles(options.outputDir, options.projectName);
// Copiar archivos del agente
this.copyAgentFiles(options.outputDir, agent);
// Generar archivos de configuración específicos
this.generateProjectFiles(options.outputDir, agent, options.projectName);
// Instalar dependencias automáticamente
await this.installDependencies(options.outputDir);
console.log(`✅ Agente compilado en: ${options.outputDir}`);
}
ensureDirectory(dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
copyBaseFiles(outputDir, projectName) {
for (const [filename, content] of Object.entries(this.baseFiles)) {
const filePath = path.join(outputDir, filename);
const fileDir = path.dirname(filePath);
this.ensureDirectory(fileDir);
let processedContent = content;
if (filename === 'package.json') {
processedContent = content.replace('{{PROJECT_NAME}}', projectName);
}
fs.writeFileSync(filePath, processedContent, 'utf-8');
}
}
copyAgentFiles(outputDir, agent) {
for (const [filename, content] of Object.entries(agent.files)) {
const filePath = path.join(outputDir, filename);
const fileDir = path.dirname(filePath);
this.ensureDirectory(fileDir);
fs.writeFileSync(filePath, content, 'utf-8');
}
}
generateProjectFiles(outputDir, agent, projectName) {
// Generar requirements.txt con dependencias del agente
const requirementsPath = path.join(outputDir, 'requirements.txt');
const requirements = agent.dependencies.join('\n');
fs.writeFileSync(requirementsPath, requirements, 'utf-8');
// Actualizar package.json con scripts del agente
const packageJsonPath = path.join(outputDir, 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
packageJson.scripts = { ...packageJson.scripts, ...agent.scripts };
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf-8');
}
generatePackageJson() {
return `{
"name": "{{PROJECT_NAME}}",
"version": "1.0.0",
"description": "Agente PersonnnKit",
"main": "runtime/dev-server.js",
"scripts": {
"dev": "node runtime/dev-server.js",
"build": "node runtime/build.js",
"start": "npm run dev",
"test": "python -m pytest tests/ -v",
"setup": "npm run install:all",
"install:all": "npm run install:node && npm run install:python",
"install:node": "npm install --only=prod",
"install:python": "bash scripts/install-python.sh",
"postinstall": "npm run install:python"
},
"dependencies": {
"express": "^4.18.2",
"cors": "^2.8.5",
"body-parser": "^1.20.2"
},
"keywords": ["personnnkit", "ai", "agent"],
"author": "",
"license": "MIT"
}`;
}
generateDevServer() {
return `const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const { spawn } = require('child_process');
const app = express();
const PORT = process.env.PORT || 3333;
// Verificar que las dependencias estén instaladas
try {
require.resolve('express');
require.resolve('cors');
require.resolve('body-parser');
} catch (error) {
console.error('❌ Error: Dependencias no instaladas');
console.error('');
console.error('🔧 Para solucionarlo, ejecuta:');
console.error(' npm install');
console.error(' o');
console.error(' npm run setup');
console.error('');
console.error('📚 Luego ejecuta nuevamente:');
console.error(' npm run dev');
process.exit(1);
}
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public'));
// Servir páginas HTML
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../pages/index.html'));
});
// API para ejecutar scripts Python
app.post('/api/run-script', async (req, res) => {
const { script, args = [] } = req.body;
try {
const scriptPath = path.join(__dirname, '../scripts', script);
const python = spawn('python3', [scriptPath, ...args]);
let output = '';
let error = '';
python.stdout.on('data', (data) => {
output += data.toString();
});
python.stderr.on('data', (data) => {
error += data.toString();
});
python.on('close', (code) => {
if (code === 0) {
try {
// Intentar parsear JSON del output
const lines = output.split('\\n');
const jsonStart = lines.findIndex(line => line.includes('JSON OUTPUT:'));
if (jsonStart !== -1) {
const jsonOutput = lines.slice(jsonStart + 1).join('\\n');
const parsed = JSON.parse(jsonOutput);
res.json(parsed);
} else {
res.json({ status: 'success', output });
}
} catch (e) {
res.json({ status: 'success', output });
}
} else {
res.status(500).json({ status: 'error', error: error || 'Script failed' });
}
});
} catch (err) {
res.status(500).json({ status: 'error', error: err.message });
}
});
// API de ping
app.get('/api/ping', (req, res) => {
res.send('PersonnnKit Agent API - Online ✅');
});
app.listen(PORT, () => {
console.log(\`🚀 PersonnnKit Agent running on http://localhost:\${PORT}\`);
});`;
}
generateApiServer() {
return `// API personalizada para el agente
// Agrega aquí tus endpoints específicos
module.exports = {
// Funciones de API personalizadas
};`;
}
generatePythonInstaller() {
return `#!/bin/bash
echo "🐍 Configurando entorno Python para PersonnnKit..."
# Verificar si Python3 está instalado
if ! command -v python3 &> /dev/null; then
echo "❌ Python3 no está instalado. Instalando..."
# Detectar el sistema operativo
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
sudo apt-get update
sudo apt-get install -y python3 python3-pip python3-venv
elif [[ "$OSTYPE" == "darwin"* ]]; then
# macOS
if ! command -v brew &> /dev/null; then
echo "❌ Homebrew no está instalado. Instálalo desde https://brew.sh/"
exit 1
fi
brew install python3
else
echo "❌ Sistema operativo no soportado"
exit 1
fi
fi
# Crear entorno virtual si no existe
if [ ! -d "venv" ]; then
echo "📦 Creando entorno virtual..."
python3 -m venv venv
fi
# Activar entorno virtual
echo "🔄 Activando entorno virtual..."
source venv/bin/activate
# Actualizar pip
echo "⬆️ Actualizando pip..."
pip install --upgrade pip
# Instalar dependencias
if [ -f "requirements.txt" ]; then
echo "📥 Instalando dependencias Python..."
pip install -r requirements.txt
else
echo "⚠️ No se encontró requirements.txt"
fi
echo "✅ Configuración Python completada!"
echo "💡 Para activar el entorno virtual manualmente: source venv/bin/activate"`;
}
generateGitignore() {
return `# Dependencies
node_modules/
venv/
__pycache__/
# Environment
.env
.env.local
# Data
data/
*.log
# OS
.DS_Store
Thumbs.db
# IDE
.vscode/
.idea/`;
}
installDependencies(outputDir) {
return new Promise((resolve, reject) => {
console.log('📦 Instalando dependencias de Node.js...');
try {
const npmInstall = (0, child_process_1.spawn)('npm', ['install'], {
cwd: outputDir,
stdio: 'inherit'
});
npmInstall.on('close', (code) => {
if (code === 0) {
console.log('✅ Dependencias de Node.js instaladas exitosamente');
resolve();
}
else {
console.log('⚠️ Error al instalar dependencias. Ejecuta "npm install" manualmente en el proyecto.');
resolve(); // Don't reject, just warn
}
});
npmInstall.on('error', (error) => {
console.log('⚠️ No se pudieron instalar las dependencias automáticamente. Ejecuta "npm install" manualmente en el proyecto.');
resolve(); // Don't reject, just warn
});
}
catch (error) {
console.log('⚠️ No se pudieron instalar las dependencias automáticamente. Ejecuta "npm install" manualmente en el proyecto.');
resolve(); // Don't reject, just warn
}
});
}
}
exports.TemplateCompiler = TemplateCompiler;
async function compileAgent(agentId, projectName, outputDir) {
const compiler = new TemplateCompiler();
await compiler.compile({
agentId,
projectName,
outputDir
});
}
function listAvailableAgents() {
console.log('🤖 Agentes disponibles en PersonnnKit:\n');
const categories = [...new Set(index_1.availableAgents.map(a => a.category))];
categories.forEach(category => {
console.log(`📁 ${category.toUpperCase()}`);
const agentsInCategory = index_1.availableAgents.filter(a => a.category === category);
agentsInCategory.forEach(agent => {
console.log(` • ${agent.id} - ${agent.name}`);
console.log(` ${agent.description}`);
});
console.log('');
});
}
function getAgentInfo(agentId) {
const agent = index_1.availableAgents.find(a => a.id === agentId);
return agent || null;
}
//# sourceMappingURL=compiler.js.map