plazbot-cli 0.1.3 → 0.1.4

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 (51) hide show
  1. package/.claude/settings.local.json +14 -0
  2. package/CLAUDE.md +92 -0
  3. package/README.md +1 -1
  4. package/dist/cli.js +14 -5
  5. package/dist/commands/agent/ai-config.js +107 -0
  6. package/dist/commands/agent/chat.js +130 -34
  7. package/dist/commands/agent/copy.js +37 -0
  8. package/dist/commands/agent/create.js +80 -17
  9. package/dist/commands/agent/files.js +142 -0
  10. package/dist/commands/agent/index.js +14 -2
  11. package/dist/commands/agent/set.js +127 -0
  12. package/dist/commands/agent/templates.js +240 -0
  13. package/dist/commands/agent/tools.js +161 -0
  14. package/dist/commands/agent/wizard.js +369 -0
  15. package/dist/commands/whatsapp/broadcast.js +97 -0
  16. package/dist/commands/whatsapp/channels.js +86 -0
  17. package/dist/commands/whatsapp/chat.js +74 -0
  18. package/dist/commands/whatsapp/index.js +11 -2
  19. package/dist/commands/whatsapp/send-template.js +51 -14
  20. package/dist/commands/whatsapp/send.js +10 -10
  21. package/dist/commands/whatsapp/widget.js +64 -0
  22. package/dist/utils/banner.js +87 -0
  23. package/dist/utils/logger.js +27 -6
  24. package/dist/utils/ui.js +111 -0
  25. package/package.json +10 -2
  26. package/src/cli.ts +13 -5
  27. package/src/commands/agent/ai-config.ts +112 -0
  28. package/src/commands/agent/chat.ts +149 -40
  29. package/src/commands/agent/copy.ts +40 -0
  30. package/src/commands/agent/create.ts +58 -23
  31. package/src/commands/agent/files.ts +158 -0
  32. package/src/commands/agent/index.ts +14 -2
  33. package/src/commands/agent/set.ts +137 -0
  34. package/src/commands/agent/templates.ts +249 -0
  35. package/src/commands/agent/tools.ts +167 -0
  36. package/src/commands/agent/wizard.ts +475 -0
  37. package/src/commands/whatsapp/broadcast.ts +100 -0
  38. package/src/commands/whatsapp/channels.ts +98 -0
  39. package/src/commands/whatsapp/chat.ts +77 -0
  40. package/src/commands/whatsapp/index.ts +11 -2
  41. package/src/commands/whatsapp/send-template.ts +57 -19
  42. package/src/commands/whatsapp/send.ts +15 -14
  43. package/src/commands/whatsapp/widget.ts +67 -0
  44. package/src/utils/banner.ts +94 -0
  45. package/src/utils/logger.ts +26 -7
  46. package/src/utils/ui.ts +109 -0
  47. package/dist/commands/message/delete-webhook.js +0 -39
  48. package/dist/commands/message/index.js +0 -14
  49. package/dist/commands/message/register-webhook.js +0 -42
  50. package/dist/commands/message/send-template.js +0 -42
  51. package/dist/commands/message/send.js +0 -42
package/src/cli.ts CHANGED
@@ -4,14 +4,15 @@ import { portalCommands } from './commands/portal';
4
4
  import { authCommands } from './commands/auth';
5
5
  import { agentCommands } from './commands/agent';
6
6
  import { whatsappCommands } from './commands/whatsapp';
7
+ import { showBanner } from './utils/banner';
7
8
 
8
- // Configuración básica del CLI
9
+ // Configuracion basica del CLI
9
10
  program
10
11
  .name('plazbot')
11
- .description('CLI para manejar agentes Plazbot')
12
- .version('0.1.0');
12
+ .description('CLI oficial de Plazbot - Agentes de IA para WhatsApp, portales y desarrolladores')
13
+ .version('0.2.0');
13
14
 
14
- // Registrar todos los comandos de autenticación
15
+ // Registrar todos los comandos de autenticacion
15
16
  authCommands.forEach(cmd => program.addCommand(cmd));
16
17
 
17
18
  // Registrar todos los comandos de agente
@@ -23,4 +24,11 @@ program.addCommand(portalCommands);
23
24
  // Registrar todos los comandos de WhatsApp
24
25
  program.addCommand(whatsappCommands);
25
26
 
26
- program.parse(process.argv);
27
+ // Si no se pasan argumentos, mostrar banner
28
+ if (process.argv.length <= 2) {
29
+ showBanner().then(() => {
30
+ program.outputHelp();
31
+ });
32
+ } else {
33
+ program.parse(process.argv);
34
+ }
@@ -0,0 +1,112 @@
1
+ import { Command } from 'commander';
2
+ import { Agent } from 'plazbot';
3
+ import inquirer from 'inquirer';
4
+ import { getStoredCredentials } from '../../utils/credentials';
5
+ import { logger } from '../../utils/logger';
6
+ import { createSpinner, theme, section, kvPair } from '../../utils/ui';
7
+ import { AgentCommandOptions } from '../../types/agent';
8
+
9
+ const MODELS: Record<string, string[]> = {
10
+ openai: ['gpt-4o', 'gpt-4', 'gpt-3.5-turbo', 'o1-preview', 'o1-mini'],
11
+ claude: ['claude-3-5-sonnet-20241022', 'claude-3-opus-20240229', 'claude-3-haiku-20240307'],
12
+ gemini: ['gemini-2.0-flash', 'gemini-1.5-pro', 'gemini-1.5-flash'],
13
+ };
14
+
15
+ export const aiConfigCommand = new Command('ai-config')
16
+ .description('Configurar proveedor de IA del agente')
17
+ .argument('<agentId>', 'ID del agente')
18
+ .option('--dev', 'Usar ambiente de desarrollo', false)
19
+ .action(async (agentId: string, options: AgentCommandOptions) => {
20
+ try {
21
+ const credentials = await getStoredCredentials();
22
+ const agent = new Agent({
23
+ workspaceId: credentials.workspace,
24
+ apiKey: credentials.apiKey,
25
+ zone: credentials.zone,
26
+ ...(options.dev && { customUrl: "http://localhost:5090" })
27
+ });
28
+
29
+ const spinner = createSpinner('Cargando agente...');
30
+ spinner.start();
31
+ const agentData = await agent.getAgentById({ id: agentId });
32
+ spinner.stop();
33
+
34
+ console.log(section('Configuracion de IA - ' + (agentData.name || agentId)));
35
+
36
+ const currentProviders = agentData.aiProviders || [];
37
+ if (currentProviders.length > 0 && agentData.customAIConfig) {
38
+ console.log(theme.bold('\n Configuracion actual:'));
39
+ currentProviders.forEach((p: any) => {
40
+ console.log(kvPair(' Proveedor', p.provider));
41
+ console.log(kvPair(' Modelo', p.model));
42
+ console.log(kvPair(' Temperatura', String(p.temperature)));
43
+ console.log(kvPair(' Max Tokens', String(p.maxTokens)));
44
+ console.log(kvPair(' Default', p.isDefault ? 'Si' : 'No'));
45
+ });
46
+ } else {
47
+ console.log(theme.muted('\n Usando configuracion de IA por defecto (Plazbot)'));
48
+ }
49
+
50
+ const { action } = await (inquirer as any).prompt([{
51
+ type: 'list',
52
+ name: 'action',
53
+ message: 'Que deseas hacer?',
54
+ choices: [
55
+ { name: 'Configurar nuevo proveedor', value: 'set' },
56
+ { name: 'Usar configuracion por defecto', value: 'reset' },
57
+ { name: 'Salir', value: 'exit' },
58
+ ],
59
+ }]);
60
+
61
+ if (action === 'exit') return;
62
+
63
+ if (action === 'reset') {
64
+ const resetConfig = { ...agentData, customAIConfig: false, aiProviders: [] };
65
+ delete resetConfig.id;
66
+ delete resetConfig._id;
67
+ const resetSpinner = createSpinner('Reseteando configuracion...');
68
+ resetSpinner.start();
69
+ await agent.updateAgent(agentId, resetConfig);
70
+ resetSpinner.succeed('Usando configuracion por defecto');
71
+ return;
72
+ }
73
+
74
+ // Configurar nuevo proveedor
75
+ const ai = await (inquirer as any).prompt([
76
+ { type: 'list', name: 'provider', message: 'Proveedor:', choices: ['openai', 'claude', 'gemini'] },
77
+ ]);
78
+
79
+ const models = MODELS[ai.provider] || MODELS.openai;
80
+
81
+ const config = await (inquirer as any).prompt([
82
+ { type: 'list', name: 'model', message: 'Modelo:', choices: models },
83
+ { type: 'password', name: 'apiToken', message: 'API Token:', mask: '*', validate: (v: string) => v.length > 0 || 'Requerido' },
84
+ { type: 'number', name: 'temperature', message: 'Temperatura (0-2):', default: 0.7 },
85
+ { type: 'number', name: 'maxTokens', message: 'Max tokens (1024-16384):', default: 4096 },
86
+ ]);
87
+
88
+ const updatedConfig = {
89
+ ...agentData,
90
+ customAIConfig: true,
91
+ aiProviders: [{
92
+ provider: ai.provider,
93
+ model: config.model,
94
+ apiToken: config.apiToken,
95
+ temperature: config.temperature,
96
+ maxTokens: config.maxTokens,
97
+ isDefault: true,
98
+ }],
99
+ };
100
+ delete updatedConfig.id;
101
+ delete updatedConfig._id;
102
+ const updateSpinner = createSpinner('Guardando configuracion...');
103
+ updateSpinner.start();
104
+ await agent.updateAgent(agentId, updatedConfig);
105
+ updateSpinner.succeed(`Proveedor configurado: ${ai.provider} / ${config.model}`);
106
+
107
+ } catch (error) {
108
+ const message = error instanceof Error ? error.message : 'Error desconocido';
109
+ logger.error(message);
110
+ process.exit(1);
111
+ }
112
+ });
@@ -3,24 +3,34 @@ import { Agent } from 'plazbot';
3
3
  import { getStoredCredentials } from '../../utils/credentials';
4
4
  import { logger } from '../../utils/logger';
5
5
  import { AgentCommandOptions, AgentResponse, AgentSource } from '../../types/agent';
6
+ import { theme, section } from '../../utils/ui';
6
7
  import crypto from 'crypto';
7
8
  import readline from 'readline';
9
+ import chalk from 'chalk';
10
+
11
+ const COMMANDS_HELP = `
12
+ ${chalk.bold('Comandos disponibles:')}
13
+ ${chalk.hex('#4CAF50')('/exit')} Terminar conversacion
14
+ ${chalk.hex('#4CAF50')('/clear')} Limpiar pantalla
15
+ ${chalk.hex('#4CAF50')('/info')} Informacion de la sesion
16
+ ${chalk.hex('#4CAF50')('/sources')} Mostrar/ocultar fuentes
17
+ ${chalk.hex('#4CAF50')('/help')} Mostrar estos comandos
18
+ `;
8
19
 
9
20
  export const chatCommand = new Command('chat')
10
- .description('Inicia una sesión de chat interactiva con un agente')
21
+ .description('Inicia una sesion de chat interactiva con un agente')
11
22
  .requiredOption('-a, --agent-id <id>', 'ID del agente')
12
- .option('-s, --session-id <id>', 'ID de sesión (opcional)')
13
- .option('-m, --multiple-answers', 'Permitir múltiples respuestas', false)
23
+ .option('-s, --session-id <id>', 'ID de sesion (opcional)')
24
+ .option('-m, --multiple-answers', 'Permitir multiples respuestas', false)
14
25
  .option('--dev', 'Usar ambiente de desarrollo', false)
15
- .action(async (options: AgentCommandOptions & {
26
+ .action(async (options: AgentCommandOptions & {
16
27
  agentId: string;
17
28
  sessionId?: string;
18
29
  multipleAnswers?: boolean;
19
30
  }) => {
20
31
  try {
21
- // Obtener credenciales guardadas
22
32
  const credentials = await getStoredCredentials();
23
-
33
+
24
34
  const agent = new Agent({
25
35
  workspaceId: credentials.workspace,
26
36
  apiKey: credentials.apiKey,
@@ -28,76 +38,175 @@ export const chatCommand = new Command('chat')
28
38
  ...(options.dev && { customUrl: "http://localhost:5090" })
29
39
  });
30
40
 
31
- // Generar un sessionId si no se proporcionó uno
32
41
  const sessionId = options.sessionId || crypto.randomUUID();
42
+ let showSources = true;
43
+
44
+ // Cargar info del agente
45
+ let agentInfo: any = null;
46
+ try {
47
+ process.stdout.write(chalk.gray(' Conectando con agente...'));
48
+ agentInfo = await agent.getAgentById({ id: options.agentId });
49
+ process.stdout.write('\r' + ' '.repeat(40) + '\r');
50
+ } catch {
51
+ process.stdout.write('\r' + ' '.repeat(40) + '\r');
52
+ }
33
53
 
34
- // Crear interfaz de readline
35
54
  const rl = readline.createInterface({
36
55
  input: process.stdin,
37
56
  output: process.stdout
38
57
  });
39
58
 
40
- // Limpiar la pantalla
59
+ // Pantalla de chat
41
60
  console.clear();
61
+ const agentName = agentInfo?.name || 'Agente';
62
+ const toolCalling = agentInfo?.useToolCalling ? chalk.hex('#4CAF50')(' [Tool Calling]') : '';
63
+
64
+ console.log();
65
+ console.log(chalk.hex('#4CAF50')(' ┌' + '─'.repeat(58) + '┐'));
66
+ console.log(chalk.hex('#4CAF50')(' │') + chalk.bold(` ${agentName}${toolCalling}`).padEnd(68) + chalk.hex('#4CAF50')('│'));
67
+ console.log(chalk.hex('#4CAF50')(' │') + chalk.gray(` Session: ${sessionId.substring(0, 8)}...`).padEnd(68) + chalk.hex('#4CAF50')('│'));
68
+ console.log(chalk.hex('#4CAF50')(' │') + chalk.gray(' /help para ver comandos').padEnd(68) + chalk.hex('#4CAF50')('│'));
69
+ console.log(chalk.hex('#4CAF50')(' └' + '─'.repeat(58) + '┘'));
70
+ console.log();
71
+
72
+ // Saludo del agente
73
+ if (agentInfo?.instructions?.greeting) {
74
+ const timestamp = new Date().toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
75
+ console.log(chalk.hex('#4CAF50')(` ${agentName}`) + chalk.gray(` ${timestamp}`));
76
+ console.log(chalk.white(` ${agentInfo.instructions.greeting}`));
77
+ console.log();
78
+ }
42
79
 
43
- // Mostrar encabezado
44
- console.log('Chat session initialized\n');
45
- console.log('┌' + '─'.repeat(60) + '┐');
46
- console.log('│' + ' Plazbot Agent Chat'.padEnd(59) + '│');
47
- console.log('│' + ''.padEnd(59) + '│');
48
- console.log('│' + ' Type your messages and press Enter to send.'.padEnd(59) + '│');
49
- console.log('│' + ' Type "/exit" or press Ctrl+C to end the conversation.'.padEnd(59) + '│');
50
- console.log('└' + '─'.repeat(60) + '┘\n');
51
- console.log('Session ID:', sessionId, '\n');
52
-
53
- // Función para preguntar
54
80
  const askQuestion = () => {
55
- rl.question('You: ', async (question) => {
81
+ rl.question(chalk.hex('#2196F3')(' Tu > '), async (question) => {
82
+ if (!question.trim()) {
83
+ askQuestion();
84
+ return;
85
+ }
86
+
87
+ // Comandos especiales
56
88
  if (question.toLowerCase() === '/exit') {
57
- console.log('\nChat session ended.');
89
+ console.log(chalk.gray('\n Sesion terminada.\n'));
58
90
  rl.close();
59
91
  return;
60
92
  }
61
93
 
94
+ if (question.toLowerCase() === '/clear') {
95
+ console.clear();
96
+ askQuestion();
97
+ return;
98
+ }
99
+
100
+ if (question.toLowerCase() === '/help') {
101
+ console.log(COMMANDS_HELP);
102
+ askQuestion();
103
+ return;
104
+ }
105
+
106
+ if (question.toLowerCase() === '/info') {
107
+ console.log(section('Informacion de sesion'));
108
+ logger.label('Agent ID', options.agentId);
109
+ logger.label('Session ID', sessionId);
110
+ logger.label('Agente', agentName);
111
+ logger.label('Tool Calling', agentInfo?.useToolCalling ? 'Activado' : 'Desactivado');
112
+ logger.label('AI Provider', agentInfo?.customAIConfig ? (agentInfo.aiProviders?.[0]?.provider || 'Custom') : 'Default');
113
+ console.log();
114
+ askQuestion();
115
+ return;
116
+ }
117
+
118
+ if (question.toLowerCase() === '/sources') {
119
+ showSources = !showSources;
120
+ console.log(chalk.gray(` Fuentes: ${showSources ? 'activadas' : 'desactivadas'}`));
121
+ console.log();
122
+ askQuestion();
123
+ return;
124
+ }
125
+
62
126
  try {
63
- console.log('⋮ Waiting for response...');
64
-
127
+ process.stdout.write(chalk.gray(' ...pensando\n'));
128
+
65
129
  const response = await agent.onMessage({
66
130
  agentId: options.agentId,
67
131
  question,
68
132
  sessionId,
69
133
  multipleAnswers: options.multipleAnswers
70
- }) as AgentResponse;
134
+ }) as AgentResponse & { actionsExecuted?: any[] };
71
135
 
72
- console.log('\nAssistant:');
73
- console.log(' ' + response.answer);
74
- console.log(); // Línea en blanco para separar mensajes
136
+ const timestamp = new Date().toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
75
137
 
76
- // Si hay fuentes, mostrarlas
77
- if (response.sources && response.sources.length > 0) {
78
- console.log('Sources:');
138
+ // Mostrar tool calls si hay
139
+ if (response.actionsExecuted && response.actionsExecuted.length > 0) {
140
+ response.actionsExecuted.forEach((action: any) => {
141
+ console.log(chalk.hex('#FFA726')(` ⚡ Tool: ${action.name || action.intent || 'action'}`));
142
+ });
143
+ }
144
+
145
+ // Respuesta del agente
146
+ console.log();
147
+ console.log(chalk.hex('#4CAF50')(` ${agentName}`) + chalk.gray(` ${timestamp}`));
148
+
149
+ // Formatear respuesta (soporte basico de markdown)
150
+ const formattedAnswer = formatResponse(response.answer);
151
+ console.log(formattedAnswer);
152
+ console.log();
153
+
154
+ // Fuentes
155
+ if (showSources && response.sources && response.sources.length > 0) {
156
+ console.log(chalk.gray(' Fuentes:'));
79
157
  response.sources.forEach((source: AgentSource) => {
80
- console.log(` - ${source.title || 'Untitled'}`);
81
- if (source.url) console.log(` ${source.url}`);
158
+ console.log(chalk.gray(` - ${source.title || 'Sin titulo'}`));
159
+ if (source.url) console.log(chalk.gray(` ${source.url}`));
82
160
  });
83
- console.log(); // Línea en blanco después de las fuentes
161
+ console.log();
84
162
  }
85
163
 
86
- askQuestion(); // Continuar el ciclo de preguntas
164
+ askQuestion();
87
165
  } catch (error) {
88
166
  const message = error instanceof Error ? error.message : 'Error desconocido';
89
- console.error('\n Error:', message);
90
- askQuestion(); // Continuar a pesar del error
167
+ console.log(chalk.hex('#EF5350')(`\n Error: ${message}\n`));
168
+ askQuestion();
91
169
  }
92
170
  });
93
171
  };
94
172
 
95
- // Iniciar el ciclo de preguntas
96
173
  askQuestion();
97
174
 
98
175
  } catch (error) {
99
176
  const message = error instanceof Error ? error.message : 'Error desconocido';
100
- console.error('\n❌ Error:', message);
177
+ logger.error(message);
101
178
  process.exit(1);
102
179
  }
103
- });
180
+ });
181
+
182
+ function formatResponse(text: string): string {
183
+ if (!text) return '';
184
+
185
+ return text.split('\n').map(line => {
186
+ // Headers
187
+ if (line.startsWith('### ')) return chalk.bold.hex('#4CAF50')(' ' + line.substring(4));
188
+ if (line.startsWith('## ')) return chalk.bold.hex('#4CAF50')(' ' + line.substring(3));
189
+ if (line.startsWith('# ')) return chalk.bold.hex('#4CAF50')(' ' + line.substring(2));
190
+
191
+ // Bold
192
+ line = line.replace(/\*\*(.*?)\*\*/g, (_, text) => chalk.bold(text));
193
+
194
+ // Italic
195
+ line = line.replace(/\*(.*?)\*/g, (_, text) => chalk.italic(text));
196
+
197
+ // Code inline
198
+ line = line.replace(/`(.*?)`/g, (_, text) => chalk.hex('#FFA726')(text));
199
+
200
+ // List items
201
+ if (line.match(/^\s*[-*]\s/)) {
202
+ return chalk.white(' ' + line.replace(/^\s*[-*]\s/, ' • '));
203
+ }
204
+
205
+ // Numbered lists
206
+ if (line.match(/^\s*\d+\.\s/)) {
207
+ return chalk.white(' ' + line);
208
+ }
209
+
210
+ return chalk.white(' ' + line);
211
+ }).join('\n');
212
+ }
@@ -0,0 +1,40 @@
1
+ import { Command } from 'commander';
2
+ import { Agent } from 'plazbot';
3
+ import { getStoredCredentials } from '../../utils/credentials';
4
+ import { logger } from '../../utils/logger';
5
+ import { createSpinner } from '../../utils/ui';
6
+ import { AgentCommandOptions } from '../../types/agent';
7
+
8
+ export const copyCommand = new Command('copy')
9
+ .description('Clonar un agente existente')
10
+ .argument('<agentId>', 'ID del agente a clonar')
11
+ .option('--dev', 'Usar ambiente de desarrollo', false)
12
+ .action(async (agentId: string, options: AgentCommandOptions) => {
13
+ try {
14
+ const credentials = await getStoredCredentials();
15
+ const agent = new Agent({
16
+ workspaceId: credentials.workspace,
17
+ apiKey: credentials.apiKey,
18
+ zone: credentials.zone,
19
+ ...(options.dev && { customUrl: "http://localhost:5090" })
20
+ });
21
+
22
+ const spinner = createSpinner('Clonando agente...');
23
+ spinner.start();
24
+
25
+ const result = await (agent as any).copyAgent({ id: agentId });
26
+
27
+ spinner.succeed('Agente clonado exitosamente');
28
+
29
+ logger.title('Agente clonado');
30
+ if (result?.agentId || result?.id) {
31
+ logger.label('Nuevo ID', result.agentId || result.id);
32
+ }
33
+ logger.dim('\nEl agente clonado tiene el widget deshabilitado por defecto.');
34
+
35
+ } catch (error) {
36
+ const message = error instanceof Error ? error.message : 'Error desconocido';
37
+ logger.error(message);
38
+ process.exit(1);
39
+ }
40
+ });
@@ -3,17 +3,18 @@ import { Agent } from 'plazbot';
3
3
  import { getStoredCredentials } from '../../utils/credentials';
4
4
  import { logger } from '../../utils/logger';
5
5
  import { AgentCommandOptions } from '../../types/agent';
6
+ import { createSpinner } from '../../utils/ui';
7
+ import { runAgentWizard } from './wizard';
6
8
  import fs from 'fs/promises';
7
9
 
8
10
  export const createCommand = new Command('create')
9
- .description('Crea un nuevo agente en Plazbot usando el archivo de configuración')
10
- .argument('<configPath>', 'Ruta al archivo de configuración JSON')
11
+ .description('Crea un nuevo agente de IA (wizard interactivo o archivo JSON)')
12
+ .argument('[configPath]', 'Ruta al archivo de configuracion JSON (opcional)')
11
13
  .option('--dev', 'Usar ambiente de desarrollo', false)
12
- .action(async (configPath: string, options: AgentCommandOptions) => {
14
+ .action(async (configPath: string | undefined, options: AgentCommandOptions) => {
13
15
  try {
14
- // Obtener credenciales guardadas
15
16
  const credentials = await getStoredCredentials();
16
-
17
+
17
18
  const agent = new Agent({
18
19
  workspaceId: credentials.workspace,
19
20
  apiKey: credentials.apiKey,
@@ -21,28 +22,62 @@ export const createCommand = new Command('create')
21
22
  ...(options.dev && { customUrl: "http://localhost:5090" })
22
23
  });
23
24
 
24
- // Leer archivo de configuración
25
- let agentConfig;
26
- try {
27
- const fileContent = await fs.readFile(configPath, 'utf-8');
28
- agentConfig = JSON.parse(fileContent);
29
- } catch (error) {
30
- const errorMessage = error instanceof Error ? error.message : 'Error desconocido';
31
- throw new Error(`Error al leer el archivo de configuración: ${errorMessage}`);
25
+ let agentConfig: any;
26
+
27
+ if (configPath) {
28
+ // Modo archivo: leer JSON
29
+ try {
30
+ const fileContent = await fs.readFile(configPath, 'utf-8');
31
+ agentConfig = JSON.parse(fileContent);
32
+ } catch (error) {
33
+ const errorMessage = error instanceof Error ? error.message : 'Error desconocido';
34
+ throw new Error(`Error al leer el archivo de configuracion: ${errorMessage}`);
35
+ }
36
+ logger.title('Creando agente desde archivo');
37
+ logger.json(agentConfig);
38
+ } else {
39
+ // Modo wizard interactivo
40
+ agentConfig = await runAgentWizard(credentials.zone);
41
+
42
+ const inquirer = await import('inquirer');
43
+ const { confirm } = await inquirer.default.prompt([{
44
+ type: 'confirm',
45
+ name: 'confirm',
46
+ message: 'Crear el agente con esta configuracion?',
47
+ default: true,
48
+ }]);
49
+
50
+ if (!confirm) {
51
+ logger.warning('Creacion cancelada');
52
+ return;
53
+ }
32
54
  }
33
55
 
34
- logger.info('\n🤖 Creando nuevo agente...');
35
- logger.info('Configuración:');
36
- logger.info(JSON.stringify(agentConfig, null, 2));
37
-
56
+ const spinner = createSpinner('Creando agente...');
57
+ spinner.start();
58
+
38
59
  const result = await agent.addAgent(agentConfig);
39
60
 
40
- logger.success('Agente creado exitosamente');
41
- logger.info('\n📋 Detalles del agente:');
42
- logger.info(JSON.stringify(result, null, 2));
43
-
61
+ spinner.succeed('Agente creado exitosamente');
62
+
63
+ logger.title('Detalles del agente');
64
+ if (result.agentId) {
65
+ logger.label('ID', result.agentId);
66
+ }
67
+ if (agentConfig.name) {
68
+ logger.label('Nombre', agentConfig.name);
69
+ }
70
+ logger.label('Tool Calling', agentConfig.useToolCalling ? 'Activado' : 'Desactivado');
71
+
72
+ if (agentConfig.channels && agentConfig.channels.length > 0) {
73
+ logger.label('WhatsApp', agentConfig.channels[0].key);
74
+ }
75
+
76
+ console.log();
77
+ logger.dim('Siguiente paso: plazbot agent chat -a ' + (result.agentId || '<agentId>'));
78
+
44
79
  if (options.dev) {
45
- logger.warning('\nAmbiente: desarrollo');
80
+ logger.warning('Ambiente: desarrollo');
46
81
  }
47
82
 
48
83
  } catch (error) {
@@ -50,4 +85,4 @@ export const createCommand = new Command('create')
50
85
  logger.error(message);
51
86
  process.exit(1);
52
87
  }
53
- });
88
+ });