UNPKG

plazbot-cli

Version:
189 lines (188 loc) 9.44 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.chatCommand = void 0; const commander_1 = require("commander"); const plazbot_1 = require("plazbot"); const credentials_1 = require("../../utils/credentials"); const logger_1 = require("../../utils/logger"); const ui_1 = require("../../utils/ui"); const crypto_1 = __importDefault(require("crypto")); const readline_1 = __importDefault(require("readline")); const chalk_1 = __importDefault(require("chalk")); const COMMANDS_HELP = ` ${chalk_1.default.bold('Comandos disponibles:')} ${chalk_1.default.hex('#4CAF50')('/exit')} Terminar conversacion ${chalk_1.default.hex('#4CAF50')('/clear')} Limpiar pantalla ${chalk_1.default.hex('#4CAF50')('/info')} Informacion de la sesion ${chalk_1.default.hex('#4CAF50')('/sources')} Mostrar/ocultar fuentes ${chalk_1.default.hex('#4CAF50')('/help')} Mostrar estos comandos `; exports.chatCommand = new commander_1.Command('chat') .description('Inicia una sesion de chat interactiva con un agente') .requiredOption('-a, --agent-id <id>', 'ID del agente') .option('-s, --session-id <id>', 'ID de sesion (opcional)') .option('-m, --multiple-answers', 'Permitir multiples respuestas', false) .option('--dev', 'Usar ambiente de desarrollo', false) .action(async (options) => { try { const credentials = await (0, credentials_1.getStoredCredentials)(); const agent = new plazbot_1.Agent({ workspaceId: credentials.workspace, apiKey: credentials.apiKey, zone: credentials.zone, ...(options.dev && { customUrl: "http://localhost:5090" }) }); const sessionId = options.sessionId || crypto_1.default.randomUUID(); let showSources = true; // Cargar info del agente let agentInfo = null; try { process.stdout.write(chalk_1.default.gray(' Conectando con agente...')); agentInfo = await agent.getAgentById({ id: options.agentId }); process.stdout.write('\r' + ' '.repeat(40) + '\r'); } catch { process.stdout.write('\r' + ' '.repeat(40) + '\r'); } const rl = readline_1.default.createInterface({ input: process.stdin, output: process.stdout }); // Pantalla de chat console.clear(); const agentName = agentInfo?.name || 'Agente'; const toolCalling = agentInfo?.useToolCalling ? chalk_1.default.hex('#4CAF50')(' [Tool Calling]') : ''; console.log(); console.log(chalk_1.default.hex('#4CAF50')(' ┌' + '─'.repeat(58) + '┐')); console.log(chalk_1.default.hex('#4CAF50')(' │') + chalk_1.default.bold(` ${agentName}${toolCalling}`).padEnd(68) + chalk_1.default.hex('#4CAF50')('│')); console.log(chalk_1.default.hex('#4CAF50')(' │') + chalk_1.default.gray(` Session: ${sessionId.substring(0, 8)}...`).padEnd(68) + chalk_1.default.hex('#4CAF50')('│')); console.log(chalk_1.default.hex('#4CAF50')(' │') + chalk_1.default.gray(' /help para ver comandos').padEnd(68) + chalk_1.default.hex('#4CAF50')('│')); console.log(chalk_1.default.hex('#4CAF50')(' └' + '─'.repeat(58) + '┘')); console.log(); // Saludo del agente if (agentInfo?.instructions?.greeting) { const timestamp = new Date().toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' }); console.log(chalk_1.default.hex('#4CAF50')(` ${agentName}`) + chalk_1.default.gray(` ${timestamp}`)); console.log(chalk_1.default.white(` ${agentInfo.instructions.greeting}`)); console.log(); } const askQuestion = () => { rl.question(chalk_1.default.hex('#2196F3')(' Tu > '), async (question) => { if (!question.trim()) { askQuestion(); return; } // Comandos especiales if (question.toLowerCase() === '/exit') { console.log(chalk_1.default.gray('\n Sesion terminada.\n')); rl.close(); return; } if (question.toLowerCase() === '/clear') { console.clear(); askQuestion(); return; } if (question.toLowerCase() === '/help') { console.log(COMMANDS_HELP); askQuestion(); return; } if (question.toLowerCase() === '/info') { console.log((0, ui_1.section)('Informacion de sesion')); logger_1.logger.label('Agent ID', options.agentId); logger_1.logger.label('Session ID', sessionId); logger_1.logger.label('Agente', agentName); logger_1.logger.label('Tool Calling', agentInfo?.useToolCalling ? 'Activado' : 'Desactivado'); logger_1.logger.label('AI Provider', agentInfo?.customAIConfig ? (agentInfo.aiProviders?.[0]?.provider || 'Custom') : 'Default'); console.log(); askQuestion(); return; } if (question.toLowerCase() === '/sources') { showSources = !showSources; console.log(chalk_1.default.gray(` Fuentes: ${showSources ? 'activadas' : 'desactivadas'}`)); console.log(); askQuestion(); return; } try { process.stdout.write(chalk_1.default.gray(' ...pensando\n')); const response = await agent.onMessage({ agentId: options.agentId, question, sessionId, multipleAnswers: options.multipleAnswers }); const timestamp = new Date().toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' }); // Mostrar tool calls si hay if (response.actionsExecuted && response.actionsExecuted.length > 0) { response.actionsExecuted.forEach((action) => { console.log(chalk_1.default.hex('#FFA726')(` ⚡ Tool: ${action.name || action.intent || 'action'}`)); }); } // Respuesta del agente console.log(); console.log(chalk_1.default.hex('#4CAF50')(` ${agentName}`) + chalk_1.default.gray(` ${timestamp}`)); // Formatear respuesta (soporte basico de markdown) const formattedAnswer = formatResponse(response.answer); console.log(formattedAnswer); console.log(); // Fuentes if (showSources && response.sources && response.sources.length > 0) { console.log(chalk_1.default.gray(' Fuentes:')); response.sources.forEach((source) => { console.log(chalk_1.default.gray(` - ${source.title || 'Sin titulo'}`)); if (source.url) console.log(chalk_1.default.gray(` ${source.url}`)); }); console.log(); } askQuestion(); } catch (error) { const message = error instanceof Error ? error.message : 'Error desconocido'; console.log(chalk_1.default.hex('#EF5350')(`\n ✖ Error: ${message}\n`)); askQuestion(); } }); }; askQuestion(); } catch (error) { const message = error instanceof Error ? error.message : 'Error desconocido'; logger_1.logger.error(message); process.exit(1); } }); function formatResponse(text) { if (!text) return ''; return text.split('\n').map(line => { // Headers if (line.startsWith('### ')) return chalk_1.default.bold.hex('#4CAF50')(' ' + line.substring(4)); if (line.startsWith('## ')) return chalk_1.default.bold.hex('#4CAF50')(' ' + line.substring(3)); if (line.startsWith('# ')) return chalk_1.default.bold.hex('#4CAF50')(' ' + line.substring(2)); // Bold line = line.replace(/\*\*(.*?)\*\*/g, (_, text) => chalk_1.default.bold(text)); // Italic line = line.replace(/\*(.*?)\*/g, (_, text) => chalk_1.default.italic(text)); // Code inline line = line.replace(/`(.*?)`/g, (_, text) => chalk_1.default.hex('#FFA726')(text)); // List items if (line.match(/^\s*[-*]\s/)) { return chalk_1.default.white(' ' + line.replace(/^\s*[-*]\s/, ' • ')); } // Numbered lists if (line.match(/^\s*\d+\.\s/)) { return chalk_1.default.white(' ' + line); } return chalk_1.default.white(' ' + line); }).join('\n'); }