plazbot-cli 0.1.2

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 (76) hide show
  1. package/agent.config.json +21 -0
  2. package/dist/cli.js +22 -0
  3. package/dist/commands/agent/chat.js +92 -0
  4. package/dist/commands/agent/create.js +52 -0
  5. package/dist/commands/agent/delete.js +61 -0
  6. package/dist/commands/agent/enable-widget.js +55 -0
  7. package/dist/commands/agent/get.js +161 -0
  8. package/dist/commands/agent/index.js +22 -0
  9. package/dist/commands/agent/list.js +47 -0
  10. package/dist/commands/agent/on-message.js +67 -0
  11. package/dist/commands/agent/update.js +52 -0
  12. package/dist/commands/auth/index.js +9 -0
  13. package/dist/commands/auth/login.js +52 -0
  14. package/dist/commands/auth/logout.js +23 -0
  15. package/dist/commands/message/delete-webhook.js +39 -0
  16. package/dist/commands/message/index.js +14 -0
  17. package/dist/commands/message/register-webhook.js +42 -0
  18. package/dist/commands/message/send-template.js +42 -0
  19. package/dist/commands/message/send.js +42 -0
  20. package/dist/commands/portal/add-agent.js +58 -0
  21. package/dist/commands/portal/add-link.js +33 -0
  22. package/dist/commands/portal/clear-links.js +27 -0
  23. package/dist/commands/portal/create.js +51 -0
  24. package/dist/commands/portal/delete.js +58 -0
  25. package/dist/commands/portal/get.js +66 -0
  26. package/dist/commands/portal/index.js +22 -0
  27. package/dist/commands/portal/list.js +65 -0
  28. package/dist/commands/portal/update.js +79 -0
  29. package/dist/commands/whatsapp/delete-webhook.js +32 -0
  30. package/dist/commands/whatsapp/index.js +14 -0
  31. package/dist/commands/whatsapp/register-webhook.js +35 -0
  32. package/dist/commands/whatsapp/send-template.js +41 -0
  33. package/dist/commands/whatsapp/send.js +42 -0
  34. package/dist/types/agent.js +2 -0
  35. package/dist/types/auth.js +2 -0
  36. package/dist/types/common.js +2 -0
  37. package/dist/types/message.js +2 -0
  38. package/dist/types/portal.js +2 -0
  39. package/dist/utils/credentials.js +33 -0
  40. package/dist/utils/logger.js +24 -0
  41. package/package.json +47 -0
  42. package/src/cli.ts +26 -0
  43. package/src/commands/agent/chat.ts +103 -0
  44. package/src/commands/agent/create.ts +53 -0
  45. package/src/commands/agent/delete.ts +64 -0
  46. package/src/commands/agent/enable-widget.ts +62 -0
  47. package/src/commands/agent/get.ts +175 -0
  48. package/src/commands/agent/index.ts +20 -0
  49. package/src/commands/agent/list.ts +52 -0
  50. package/src/commands/agent/on-message.ts +75 -0
  51. package/src/commands/agent/update.ts +53 -0
  52. package/src/commands/auth/index.ts +8 -0
  53. package/src/commands/auth/login.ts +56 -0
  54. package/src/commands/auth/logout.ts +22 -0
  55. package/src/commands/portal/add-agent.ts +66 -0
  56. package/src/commands/portal/add-link.ts +39 -0
  57. package/src/commands/portal/clear-links.ts +26 -0
  58. package/src/commands/portal/create.ts +55 -0
  59. package/src/commands/portal/delete.ts +63 -0
  60. package/src/commands/portal/get.ts +75 -0
  61. package/src/commands/portal/index.ts +20 -0
  62. package/src/commands/portal/list.ts +73 -0
  63. package/src/commands/portal/update.ts +82 -0
  64. package/src/commands/whatsapp/delete-webhook.ts +37 -0
  65. package/src/commands/whatsapp/index.ts +12 -0
  66. package/src/commands/whatsapp/register-webhook.ts +41 -0
  67. package/src/commands/whatsapp/send-template.ts +44 -0
  68. package/src/commands/whatsapp/send.ts +46 -0
  69. package/src/types/agent.ts +63 -0
  70. package/src/types/auth.ts +8 -0
  71. package/src/types/common.ts +10 -0
  72. package/src/types/message.ts +34 -0
  73. package/src/types/portal.ts +56 -0
  74. package/src/utils/credentials.ts +37 -0
  75. package/src/utils/logger.ts +21 -0
  76. package/tsconfig.json +15 -0
@@ -0,0 +1,62 @@
1
+ import { Command } from 'commander';
2
+ import { Agent } from 'plazbot';
3
+ import { getStoredCredentials } from '../../utils/credentials';
4
+ import { logger } from '../../utils/logger';
5
+ import { EnableWidgetOptions } from '../../types/agent';
6
+
7
+ export const enableCommand = new Command('enable-widget')
8
+ .description('Habilita o deshabilita el widget de un agente')
9
+ .argument('<agentId>', 'ID del agente')
10
+ .option('-d, --disable', 'Deshabilitar el widget en lugar de habilitarlo')
11
+ .option('--dev', 'Usar ambiente de desarrollo', false)
12
+ .action(async (agentId: string, options: EnableWidgetOptions) => {
13
+ try {
14
+ // Obtener credenciales guardadas
15
+ const credentials = await getStoredCredentials();
16
+
17
+ const agent = new Agent({
18
+ workspaceId: credentials.workspace,
19
+ apiKey: credentials.apiKey,
20
+ zone: credentials.zone,
21
+ ...(options.dev && { customUrl: "http://localhost:5090" })
22
+ });
23
+
24
+ // Obtener estado actual del agente
25
+ const agentDetails = await agent.getAgentById({ id: agentId });
26
+
27
+ logger.info('\n🔧 Estado actual del widget:');
28
+ logger.divider();
29
+ logger.info(`Agente: ${agentDetails.agent.name}`);
30
+ logger.divider();
31
+
32
+ // Cambiar estado
33
+ const newState = !options.disable; // Si --disable está presente, newState será false
34
+ const result = await agent.enableWidget({
35
+ id: agentId,
36
+ enable: newState
37
+ });
38
+
39
+ logger.success(`Widget ${newState ? 'habilitado' : 'deshabilitado'} exitosamente`);
40
+
41
+ logger.info('\n🔧 Respuesta del servidor:');
42
+ logger.divider();
43
+ logger.info(`Estado: ${result.success ? '✅ Exitoso' : '❌ Fallido'}`);
44
+ logger.info(`Mensaje: ${result.message}`);
45
+
46
+ if (newState && result.script) {
47
+ logger.info('\n📝 Instrucciones de instalación:');
48
+ logger.divider();
49
+ logger.info('Coloca este script debajo de la etiqueta <HEAD> en tu sitio web:');
50
+ logger.info('\n' + result.script);
51
+ }
52
+
53
+ if (options.dev) {
54
+ logger.warning('Ambiente: desarrollo');
55
+ }
56
+
57
+ } catch (error) {
58
+ const message = error instanceof Error ? error.message : 'Error desconocido al modificar el widget';
59
+ logger.error(message);
60
+ process.exit(1);
61
+ }
62
+ });
@@ -0,0 +1,175 @@
1
+ import { Command } from 'commander';
2
+ import { Agent } from 'plazbot';
3
+ import { getStoredCredentials } from '../../utils/credentials';
4
+ import { logger } from '../../utils/logger';
5
+ import { AgentCommandOptions } from '../../types/agent';
6
+
7
+ export const getCommand = new Command('get')
8
+ .description('Obtiene información detallada de un agente específico')
9
+ .argument('<agentId>', 'ID del agente a consultar')
10
+ .option('--dev', 'Usar ambiente de desarrollo', false)
11
+ .action(async (agentId: string, options: AgentCommandOptions) => {
12
+ try {
13
+ // Obtener credenciales guardadas
14
+ const credentials = await getStoredCredentials();
15
+
16
+ // Crear instancia del agente con las credenciales guardadas
17
+ const agent = new Agent({
18
+ workspaceId: credentials.workspace,
19
+ apiKey: credentials.apiKey,
20
+ zone: credentials.zone,
21
+ ...(options.dev && { customUrl: "http://localhost:5090" })
22
+ });
23
+
24
+ // Obtener detalles del agente
25
+ const agentDetails = await agent.getAgentById({ id: agentId });
26
+ const agentData = agentDetails.agent;
27
+
28
+ logger.info('\nDetalles del Agente:');
29
+ logger.doubleDivider();
30
+
31
+ // Información básica
32
+ logger.info('Información Básica:');
33
+ logger.divider();
34
+ logger.info(`ID: ${agentData.id}`);
35
+ logger.info(`Nombre: ${agentData.name}`);
36
+ logger.info(`Descripción: ${agentData.description}`);
37
+ logger.info(`Estado: ${agentData.enable ? '✅ Activo' : '❌ Inactivo'}`);
38
+ logger.info(`Zona: ${agentData.zone}`);
39
+ logger.info(`Buffer: ${agentData.buffer}`);
40
+ logger.info(`Color: ${agentData.color}`);
41
+ logger.info(`Pregunta inicial: ${agentData.question}`);
42
+ logger.info(`Zona horaria: ${agentData.timezone}`);
43
+ logger.info(`Mostrar en chat: ${agentData.showInChat ? 'Sí' : 'No'}`);
44
+
45
+ // Tags
46
+ if (agentData.tags && agentData.tags.length > 0) {
47
+ logger.info(`\nTags: ${agentData.tags.join(', ')}`);
48
+ }
49
+
50
+ // Ejemplos
51
+ if (agentData.examples && agentData.examples.length > 0) {
52
+ logger.info('\nEjemplos:');
53
+ logger.divider();
54
+ agentData.examples.forEach((example: { value: string; color: string }) => {
55
+ logger.info(`- ${example.value} (${example.color})`);
56
+ });
57
+ }
58
+
59
+ // Instrucciones
60
+ if (agentData.instructions) {
61
+ logger.info('\nInstrucciones:');
62
+ logger.divider();
63
+ const instructions = agentData.instructions;
64
+ logger.info(`Tono: ${instructions.tone}`);
65
+ logger.info(`Estilo: ${instructions.style}`);
66
+ logger.info(`Personalidad: ${instructions.personality}`);
67
+ logger.info(`Objetivo: ${instructions.objective}`);
68
+ logger.info(`Idioma: ${instructions.language}`);
69
+ logger.info(`Emojis: ${instructions.emojis ? 'Sí' : 'No'}`);
70
+ logger.info(`Formato preferido: ${instructions.preferredFormat}`);
71
+ logger.info(`Máximo de palabras: ${instructions.maxWords}`);
72
+ if (instructions.avoidTopics) {
73
+ logger.info(`Temas a evitar: ${instructions.avoidTopics.join(', ')}`);
74
+ }
75
+ logger.info(`Responder solo si sabe: ${instructions.respondOnlyIfKnows ? 'Sí' : 'No'}`);
76
+ logger.info(`Mantener tono entre mensajes: ${instructions.maintainToneBetweenMessages ? 'Sí' : 'No'}`);
77
+ logger.info(`Saludo: ${instructions.greeting}`);
78
+ }
79
+
80
+ // Persona
81
+ if (agentData.person) {
82
+ logger.info('\nPersona:');
83
+ logger.divider();
84
+ const person = agentData.person;
85
+ logger.info(`Nombre: ${person.name}`);
86
+ logger.info(`Rol: ${person.role}`);
87
+ logger.info(`Habla en primera persona: ${person.speaksInFirstPerson ? 'Sí' : 'No'}`);
88
+ logger.info(`Es humano: ${person.isHuman ? 'Sí' : 'No'}`);
89
+ }
90
+
91
+ // Fallbacks
92
+ if (agentData.fallbacks) {
93
+ logger.info('\nFallbacks:');
94
+ logger.divider();
95
+ const fallbacks = agentData.fallbacks;
96
+ logger.info(`Sin respuesta: ${fallbacks.noAnswer}`);
97
+ logger.info(`Error de servicio: ${fallbacks.serviceError}`);
98
+ logger.info(`No entiende: ${fallbacks.doNotUnderstand}`);
99
+ }
100
+
101
+ // Reglas
102
+ if (agentData.rules) {
103
+ logger.info('\nReglas:');
104
+ logger.divider();
105
+ const rules = agentData.rules;
106
+ logger.info(`No mencionar precios: ${rules.doNotMentionPrices ? 'Sí' : 'No'}`);
107
+ logger.info(`No diagnosticar: ${rules.doNotDiagnose ? 'Sí' : 'No'}`);
108
+ if (rules.doNotRespondOutsideHours) {
109
+ logger.info(`Horario de atención: ${rules.doNotRespondOutsideHours}`);
110
+ }
111
+ }
112
+
113
+ // Servicios
114
+ if (agentData.services && agentData.services.length > 0) {
115
+ logger.info('\nServicios:');
116
+ logger.divider();
117
+ agentData.services.forEach((service: any, index: number) => {
118
+ logger.info(`\nServicio ${index + 1}:`);
119
+ logger.info(`Intent: ${service.intent}`);
120
+ logger.info(`Referencia: ${service.reference}`);
121
+ logger.info(`Habilitado: ${service.enabled ? 'Sí' : 'No'}`);
122
+ logger.info(`Método: ${service.method}`);
123
+ logger.info(`Endpoint: ${service.endpoint}`);
124
+ if (service.requiredFields) {
125
+ logger.info('Campos requeridos:');
126
+ service.requiredFields.forEach((field: any) => {
127
+ logger.info(` - ${field.name} (${field.type}): ${field.description}`);
128
+ });
129
+ }
130
+ });
131
+ }
132
+
133
+ // Acciones
134
+ if (agentData.actions && agentData.actions.length > 0) {
135
+ logger.info('\nAcciones:');
136
+ logger.divider();
137
+ agentData.actions.forEach((action: any, index: number) => {
138
+ logger.info(`\nAcción ${index + 1}:`);
139
+ logger.info(`Intent: ${action.intent}`);
140
+ logger.info(`Referencia: ${action.reference}`);
141
+ logger.info(`Habilitado: ${action.enabled ? 'Sí' : 'No'}`);
142
+ if (action.tags) {
143
+ logger.info(`Tags: ${action.tags.join(', ')}`);
144
+ }
145
+ logger.info(`Mensaje de respuesta: ${action.responseMessage}`);
146
+ if (action.action) {
147
+ logger.info('Sub-acciones:');
148
+ action.action.forEach((subAction: any) => {
149
+ logger.info(` - ${subAction.type}: ${subAction.value}`);
150
+ });
151
+ }
152
+ });
153
+ }
154
+
155
+ // Canales
156
+ if (agentData.channels && agentData.channels.length > 0) {
157
+ logger.info('\nCanales:');
158
+ logger.divider();
159
+ agentData.channels.forEach((channel: { channel: string; key: string }) => {
160
+ logger.info(`${channel.channel}: ${channel.key}`);
161
+ });
162
+ }
163
+
164
+ logger.doubleDivider();
165
+
166
+ if (options.dev) {
167
+ logger.warning('Ambiente: desarrollo');
168
+ }
169
+
170
+ } catch (error) {
171
+ const message = error instanceof Error ? error.message : 'Error desconocido al obtener el agente';
172
+ logger.error(message);
173
+ process.exit(1);
174
+ }
175
+ });
@@ -0,0 +1,20 @@
1
+ import { Command } from 'commander';
2
+ import { listCommand } from './list';
3
+ import { getCommand } from './get';
4
+ import { deleteCommand } from './delete';
5
+ import { createCommand } from './create';
6
+ import { updateCommand } from './update';
7
+ import { enableCommand } from './enable-widget';
8
+ import { chatCommand } from './chat';
9
+ import { messageCommand } from './on-message';
10
+
11
+ export const agentCommands = new Command('agent')
12
+ .description('Comandos relacionados con agentes')
13
+ .addCommand(listCommand)
14
+ .addCommand(getCommand)
15
+ .addCommand(deleteCommand)
16
+ .addCommand(createCommand)
17
+ .addCommand(updateCommand)
18
+ .addCommand(enableCommand)
19
+ .addCommand(chatCommand)
20
+ .addCommand(messageCommand);
@@ -0,0 +1,52 @@
1
+ import { Command } from 'commander';
2
+ import { Agent } from 'plazbot';
3
+ import { getStoredCredentials } from '../../utils/credentials';
4
+ import { logger } from '../../utils/logger';
5
+ import { ListAgentsOptions, AgentListItem } from '../../types/agent';
6
+
7
+ export const listCommand = new Command('list')
8
+ .description('Lista todos los agentes del workspace')
9
+ .option('--dev', 'Usar ambiente de desarrollo', false)
10
+ .action(async (options: ListAgentsOptions) => {
11
+ try {
12
+ // Obtener credenciales guardadas
13
+ const credentials = await getStoredCredentials();
14
+
15
+ // Crear instancia del agente con las credenciales guardadas
16
+ const agent = new Agent({
17
+ workspaceId: credentials.workspace,
18
+ apiKey: credentials.apiKey,
19
+ zone: credentials.zone,
20
+ ...(options.dev && { customUrl: "http://localhost:5090" })
21
+ });
22
+
23
+ // Obtener lista de agentes
24
+ const agents = await agent.getAgents();
25
+
26
+ if (agents.length === 0) {
27
+ logger.info('No se encontraron agentes en este workspace');
28
+ return;
29
+ }
30
+
31
+ logger.info('\nLista de Agentes:');
32
+ logger.doubleDivider();
33
+
34
+ agents.forEach((agent: AgentListItem, index: number) => {
35
+ logger.info(`${index + 1}. ID: ${agent.id}`);
36
+ logger.info(` Nombre: ${agent.name}`);
37
+ logger.info(` Estado: ${agent.enable ? '✅ Activo' : '❌ Inactivo'}`);
38
+ logger.info(` Descripción: ${agent.description}`);
39
+ logger.info(` Creado: ${new Date(agent.createdAt).toLocaleString()}`);
40
+ logger.divider();
41
+ });
42
+
43
+ if (options.dev) {
44
+ logger.warning('Ambiente: desarrollo');
45
+ }
46
+
47
+ } catch (error) {
48
+ const message = error instanceof Error ? error.message : 'Error desconocido al listar agentes';
49
+ logger.error(message);
50
+ process.exit(1);
51
+ }
52
+ });
@@ -0,0 +1,75 @@
1
+ import { Command } from 'commander';
2
+ import { Agent } from 'plazbot';
3
+ import { getStoredCredentials } from '../../utils/credentials';
4
+ import { logger } from '../../utils/logger';
5
+ import { AgentCommandOptions, AgentResponse, AgentSource } from '../../types/agent';
6
+ import crypto from 'crypto';
7
+
8
+ export const messageCommand = new Command('message')
9
+ .description('Envía un mensaje a un agente y obtiene su respuesta')
10
+ .requiredOption('-a, --agent-id <id>', 'ID del agente')
11
+ .requiredOption('-q, --question <text>', 'Mensaje o pregunta para el agente')
12
+ .option('-s, --session-id <id>', 'ID de sesión (opcional)')
13
+ .option('-m, --multiple-answers', 'Permitir múltiples respuestas', false)
14
+ .option('--dev', 'Usar ambiente de desarrollo', false)
15
+ .action(async (options: AgentCommandOptions & {
16
+ agentId: string;
17
+ question: string;
18
+ sessionId?: string;
19
+ multipleAnswers?: boolean;
20
+ }) => {
21
+ try {
22
+ // Obtener credenciales guardadas
23
+ const credentials = await getStoredCredentials();
24
+
25
+ const agent = new Agent({
26
+ workspaceId: credentials.workspace,
27
+ apiKey: credentials.apiKey,
28
+ zone: credentials.zone,
29
+ ...(options.dev && { customUrl: "http://localhost:5090" })
30
+ });
31
+
32
+ // Generar un sessionId si no se proporcionó uno
33
+ const sessionId = options.sessionId || crypto.randomUUID();
34
+
35
+ logger.info('\n🤖 Enviando mensaje al agente...');
36
+ logger.info(`ID del agente: ${options.agentId}`);
37
+ logger.info(`Pregunta: ${options.question}`);
38
+ logger.info(`ID de sesión: ${sessionId}`);
39
+ if (options.multipleAnswers) {
40
+ logger.info('Modo: Múltiples respuestas');
41
+ }
42
+
43
+ const response = await agent.onMessage({
44
+ agentId: options.agentId,
45
+ question: options.question,
46
+ sessionId,
47
+ multipleAnswers: options.multipleAnswers
48
+ }) as AgentResponse;
49
+
50
+ logger.info('\n💬 Respuesta del Agente:');
51
+ logger.divider();
52
+ console.log(response.answer);
53
+
54
+ if (response.sources && response.sources.length > 0) {
55
+ logger.info('\n📚 Fuentes:');
56
+ logger.divider();
57
+ response.sources.forEach((source: AgentSource) => {
58
+ logger.info(`- ${source.title || 'Sin título'}`);
59
+ if (source.url) logger.info(` URL: ${source.url}`);
60
+ });
61
+ }
62
+
63
+ logger.info('\n🔑 ID de Sesión:');
64
+ logger.info(sessionId);
65
+
66
+ if (options.dev) {
67
+ logger.warning('\nAmbiente: desarrollo');
68
+ }
69
+
70
+ } catch (error) {
71
+ const message = error instanceof Error ? error.message : 'Error desconocido al enviar el mensaje';
72
+ logger.error(message);
73
+ process.exit(1);
74
+ }
75
+ });
@@ -0,0 +1,53 @@
1
+ import { Command } from 'commander';
2
+ import { Agent } from 'plazbot';
3
+ import { getStoredCredentials } from '../../utils/credentials';
4
+ import { logger } from '../../utils/logger';
5
+ import { AgentCommandOptions } from '../../types/agent';
6
+ import fs from 'fs/promises';
7
+
8
+ export const updateCommand = new Command('update')
9
+ .description('Actualiza un agente existente en Plazbot')
10
+ .argument('<agentId>', 'ID del agente a actualizar')
11
+ .argument('<configPath>', 'Ruta al archivo de configuración JSON del agente')
12
+ .option('--dev', 'Usar ambiente de desarrollo', false)
13
+ .action(async (agentId: string, configPath: string, options: AgentCommandOptions) => {
14
+ try {
15
+ // Obtener credenciales guardadas
16
+ const credentials = await getStoredCredentials();
17
+
18
+ // Leer archivo de configuración del agente
19
+ let agentConfig;
20
+ try {
21
+ const fileContent = await fs.readFile(configPath, 'utf-8');
22
+ agentConfig = JSON.parse(fileContent);
23
+ } catch (error) {
24
+ const errorMessage = error instanceof Error ? error.message : 'Error desconocido';
25
+ throw new Error(`Error al leer el archivo de configuración: ${errorMessage}`);
26
+ }
27
+
28
+ // Crear instancia del agente con las credenciales guardadas
29
+ const agent = new Agent({
30
+ workspaceId: credentials.workspace,
31
+ apiKey: credentials.apiKey,
32
+ zone: credentials.zone,
33
+ ...(options.dev && { customUrl: "http://localhost:5090" })
34
+ });
35
+
36
+ logger.info('\n🔄 Actualizando agente...');
37
+
38
+ // Actualizar el agente
39
+ const result = await agent.updateAgent(agentId, agentConfig);
40
+
41
+ logger.success('Agente actualizado exitosamente');
42
+ logger.info(`Mensaje: ${result.message}`);
43
+
44
+ if (options.dev) {
45
+ logger.warning('Ambiente: desarrollo');
46
+ }
47
+
48
+ } catch (error) {
49
+ const message = error instanceof Error ? error.message : 'Error desconocido al actualizar el agente';
50
+ logger.error(message);
51
+ process.exit(1);
52
+ }
53
+ });
@@ -0,0 +1,8 @@
1
+ import { Command } from 'commander';
2
+ import { loginCommand } from './login';
3
+ import { logoutCommand } from './logout';
4
+
5
+ export const authCommands: Command[] = [
6
+ loginCommand,
7
+ logoutCommand
8
+ ];
@@ -0,0 +1,56 @@
1
+ import { Command } from 'commander';
2
+ import { saveCredentials } from '../../utils/credentials';
3
+ import { logger } from '../../utils/logger';
4
+ import { LoginOptions } from '../../types/auth';
5
+
6
+ export const loginCommand = new Command('init')
7
+ .description('Guarda la API Key y correo del usuario localmente')
8
+ .requiredOption('-e, --email <email>', 'Correo del usuario')
9
+ .requiredOption('-k, --api-key <apiKey>', 'API Key del usuario')
10
+ .requiredOption('-w, --workspace <workspace>', 'ID del workspace')
11
+ .requiredOption('-z, --zone <zone>', 'Zona (LA o EU)')
12
+ .option('--dev', 'Usar ambiente de desarrollo', false)
13
+ .action(async (options: LoginOptions) => {
14
+ try {
15
+ // Limpiar la pantalla
16
+ console.clear();
17
+
18
+ // Banner de bienvenida
19
+ logger.info('┌' + '─'.repeat(70) + '┐');
20
+ logger.info('│' + ' Bienvenido a Plazbot CLI'.padEnd(69) + '│');
21
+ logger.info('│' + ''.padEnd(69) + '│');
22
+ logger.info('│' + ' Con esta herramienta podrás:'.padEnd(69) + '│');
23
+ logger.info('│' + ' • Crear y actualizar agentes'.padEnd(69) + '│');
24
+ logger.info('│' + ' • Gestionar configuraciones'.padEnd(69) + '│');
25
+ logger.info('│' + ' • Interactuar con tus agentes'.padEnd(69) + '│');
26
+ logger.info('│' + ' • Activar todas sus capacidades'.padEnd(69) + '│');
27
+ logger.info('└' + '─'.repeat(70) + '┘\n');
28
+
29
+ await saveCredentials({
30
+ email: options.email,
31
+ apiKey: options.apiKey,
32
+ workspace: options.workspace,
33
+ zone: options.zone
34
+ });
35
+
36
+ logger.success('Configuración guardada exitosamente:');
37
+ logger.info(' • Email: ' + options.email);
38
+ logger.info(' • Workspace: ' + options.workspace);
39
+ logger.info(' • Zona: ' + options.zone);
40
+
41
+ logger.info('\n🚀 Puedes comenzar usando los siguientes comandos:');
42
+ logger.info(' • plazbot list-agents - Ver tus agentes');
43
+ logger.info(' • plazbot create-agent - Crear un nuevo agente');
44
+ logger.info(' • plazbot chat - Chatear con un agente');
45
+ logger.info(' • plazbot --help - Ver todos los comandos\n');
46
+
47
+ if (options.dev) {
48
+ logger.warning('Ambiente: desarrollo');
49
+ }
50
+
51
+ } catch (error) {
52
+ const message = error instanceof Error ? error.message : 'Error desconocido';
53
+ logger.error(message);
54
+ process.exit(1);
55
+ }
56
+ });
@@ -0,0 +1,22 @@
1
+ import { Command } from 'commander';
2
+ import { removeCredentials } from '../../utils/credentials';
3
+ import { logger } from '../../utils/logger';
4
+ import { BaseCommandOptions } from '../../types/common';
5
+
6
+ export const logoutCommand = new Command('finish')
7
+ .description('Elimina la configuración local del usuario')
8
+ .option('--dev', 'Usar ambiente de desarrollo', false)
9
+ .action(async (options: BaseCommandOptions) => {
10
+ try {
11
+ await removeCredentials();
12
+ logger.success('Has cerrado sesión correctamente');
13
+
14
+ if (options.dev) {
15
+ logger.warning('Ambiente: desarrollo');
16
+ }
17
+ } catch (error) {
18
+ const message = error instanceof Error ? error.message : 'Error desconocido al cerrar sesión';
19
+ logger.error(message);
20
+ process.exit(1);
21
+ }
22
+ });
@@ -0,0 +1,66 @@
1
+ import { Command } from 'commander';
2
+ import { Portal, Agent } from 'plazbot';
3
+ import { getStoredCredentials } from '../../utils/credentials';
4
+ import { logger } from '../../utils/logger';
5
+ import { AddAgentToPortalOptions } from '../../types/portal';
6
+
7
+ export const addAgentCommand = new Command('add-agent-portal')
8
+ .description('Agrega un agente existente a un portal')
9
+ .requiredOption('-p, --portal-id <portalId>', 'ID del portal')
10
+ .requiredOption('-a, --agent-id <agentId>', 'ID del agente a agregar')
11
+ .option('--dev', 'Usar ambiente de desarrollo', false)
12
+ .action(async (options: AddAgentToPortalOptions) => {
13
+ try {
14
+ // Obtener credenciales guardadas
15
+ const credentials = await getStoredCredentials();
16
+
17
+ const portal = new Portal({
18
+ workspaceId: credentials.workspace,
19
+ apiKey: credentials.apiKey,
20
+ zone: credentials.zone,
21
+ ...(options.dev && { customUrl: "http://localhost:5090" })
22
+ });
23
+
24
+ // Obtener detalles del portal
25
+ const portalDetails = await portal.getPortal(options.portalId);
26
+
27
+ // Crear instancia del agente para obtener sus detalles
28
+ const agent = new Agent({
29
+ workspaceId: credentials.workspace,
30
+ apiKey: credentials.apiKey,
31
+ zone: credentials.zone,
32
+ ...(options.dev && { customUrl: "http://localhost:5090" })
33
+ });
34
+
35
+ // Obtener detalles del agente
36
+ const agentDetails = await agent.getAgentById({ id: options.agentId });
37
+
38
+ logger.info('\n📎 Detalles de la operación:');
39
+ logger.divider();
40
+ logger.info('Portal:');
41
+ logger.info(` ID: ${portalDetails.portal.id}`);
42
+ logger.info(` Nombre: ${portalDetails.portal.name}`);
43
+ logger.info('\nAgente:');
44
+ logger.info(` ID: ${agentDetails.agent.id}`);
45
+ logger.info(` Nombre: ${agentDetails.agent.name}`);
46
+ logger.divider();
47
+
48
+ logger.info('\n🔄 Agregando agente al portal...');
49
+
50
+ await portal.addAgentToPortal({
51
+ portalId: options.portalId,
52
+ id: options.agentId
53
+ });
54
+
55
+ logger.success('Agente agregado exitosamente al portal');
56
+
57
+ if (options.dev) {
58
+ logger.warning('Ambiente: desarrollo');
59
+ }
60
+
61
+ } catch (error) {
62
+ const message = error instanceof Error ? error.message : 'Error desconocido';
63
+ logger.error(message);
64
+ process.exit(1);
65
+ }
66
+ });
@@ -0,0 +1,39 @@
1
+ import { Command } from 'commander'
2
+ import { Portal } from 'plazbot'
3
+ import { getStoredCredentials } from '../../utils/credentials'
4
+ import { logger } from '../../utils/logger'
5
+ import { BaseCommandOptions } from '../../types/common'
6
+
7
+ interface AddLinkOptions extends BaseCommandOptions {
8
+ title: string
9
+ url: string
10
+ }
11
+
12
+ export const addLinkCommand = new Command('add-link')
13
+ .description('Agregar un enlace al portal')
14
+ .argument('<portalId>', 'ID del portal')
15
+ .requiredOption('-t, --title <title>', 'Título del enlace')
16
+ .requiredOption('-u, --url <url>', 'URL del enlace')
17
+ .option('--dev', 'Usar entorno de desarrollo')
18
+ .action(async (portalId: string, options: AddLinkOptions) => {
19
+ try {
20
+ const credentials = await getStoredCredentials()
21
+ const portal = new Portal({
22
+ workspaceId: credentials.workspace,
23
+ apiKey: credentials.apiKey,
24
+ zone: credentials.zone,
25
+ ...(options.dev && { customUrl: "http://localhost:5090" })
26
+ })
27
+
28
+ await portal.addLinkToPortal({
29
+ portalId,
30
+ value: options.title,
31
+ url: options.url
32
+ })
33
+
34
+ console.log('✅ Enlace agregado exitosamente')
35
+ } catch (error: unknown) {
36
+ console.error('❌ Error al agregar el enlace:', (error as Error).message)
37
+ process.exit(1)
38
+ }
39
+ })
@@ -0,0 +1,26 @@
1
+ import { Command } from 'commander';
2
+ import { Portal } from 'plazbot';
3
+ import { getStoredCredentials } from '../../utils/credentials';
4
+ import { BaseCommandOptions } from '../../types/common';
5
+
6
+ export const clearLinksCommand = new Command('clear-links')
7
+ .description('Eliminar todos los enlaces del portal')
8
+ .argument('<portalId>', 'ID del portal')
9
+ .option('--dev', 'Usar entorno de desarrollo')
10
+ .action(async (portalId: string, options: BaseCommandOptions) => {
11
+ try {
12
+ const credentials = await getStoredCredentials();
13
+ const portal = new Portal({
14
+ workspaceId: credentials.workspace,
15
+ apiKey: credentials.apiKey,
16
+ zone: credentials.zone,
17
+ ...(options.dev && { customUrl: "http://localhost:5090" })
18
+ });
19
+
20
+ await portal.clearLinks(portalId);
21
+ console.log('✅ Enlaces eliminados exitosamente');
22
+ } catch (error: unknown) {
23
+ console.error('❌ Error al eliminar los enlaces:', (error as Error).message);
24
+ process.exit(1);
25
+ }
26
+ });