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,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.updateCommand = void 0;
4
+ const commander_1 = require("commander");
5
+ const plazbot_1 = require("plazbot");
6
+ const credentials_1 = require("../../utils/credentials");
7
+ const logger_1 = require("../../utils/logger");
8
+ exports.updateCommand = new commander_1.Command('update')
9
+ .description('Actualiza un portal existente')
10
+ .argument('<portalId>', 'ID del portal a actualizar')
11
+ .option('-n, --name <name>', 'Nuevo nombre del portal')
12
+ .option('-t, --title <title>', 'Nuevo título del portal')
13
+ .option('-s, --subtitle <subtitle>', 'Nuevo subtítulo del portal')
14
+ .option('-l, --logo <url>', 'Nueva URL del logo')
15
+ .option('-d, --logo-dark <url>', 'Nueva URL del logo en modo oscuro')
16
+ .option('-a, --access <type>', 'Tipo de acceso (direct o form)')
17
+ .option('--disabled <value>', 'Estado de deshabilitación (true o false)')
18
+ .option('--brand-off <value>', 'Estado de marca deshabilitada (true o false)')
19
+ .option('--dev', 'Usar ambiente de desarrollo', false)
20
+ .action(async (portalId, options) => {
21
+ try {
22
+ // Obtener credenciales guardadas
23
+ const credentials = await (0, credentials_1.getStoredCredentials)();
24
+ const portal = new plazbot_1.Portal({
25
+ workspaceId: credentials.workspace,
26
+ apiKey: credentials.apiKey,
27
+ zone: credentials.zone,
28
+ ...(options.dev && { customUrl: "http://localhost:5090" })
29
+ });
30
+ // Obtener detalles actuales del portal
31
+ const currentPortal = await portal.getPortal(portalId);
32
+ logger_1.logger.info('\n🌐 Actualizando portal...');
33
+ logger_1.logger.info('Portal actual:');
34
+ logger_1.logger.info(JSON.stringify(currentPortal.portal, null, 2));
35
+ // Construir objeto de actualización solo con los campos proporcionados
36
+ const updateData = { id: portalId };
37
+ if (options.name)
38
+ updateData.name = options.name;
39
+ if (options.title)
40
+ updateData.title = options.title;
41
+ if (options.subtitle)
42
+ updateData.subtitle = options.subtitle;
43
+ if (options.logo)
44
+ updateData.logo = options.logo;
45
+ if (options.logoDark)
46
+ updateData.logodark = options.logoDark;
47
+ if (options.access) {
48
+ if (options.access !== 'direct' && options.access !== 'form') {
49
+ throw new Error('El tipo de acceso debe ser "direct" o "form"');
50
+ }
51
+ updateData.access = options.access;
52
+ }
53
+ if (options.disabled) {
54
+ if (options.disabled !== 'true' && options.disabled !== 'false') {
55
+ throw new Error('El valor de disabled debe ser "true" o "false"');
56
+ }
57
+ updateData.disabled = options.disabled === 'true';
58
+ }
59
+ if (options.brandOff) {
60
+ if (options.brandOff !== 'true' && options.brandOff !== 'false') {
61
+ throw new Error('El valor de brand-off debe ser "true" o "false"');
62
+ }
63
+ updateData.brandOff = options.brandOff === 'true';
64
+ }
65
+ logger_1.logger.info('\nCambios a aplicar:');
66
+ logger_1.logger.info(JSON.stringify(updateData, null, 2));
67
+ const result = await portal.updatePortal(updateData);
68
+ logger_1.logger.success('Portal actualizado exitosamente');
69
+ logger_1.logger.info(`Mensaje: ${result.message}`);
70
+ if (options.dev) {
71
+ logger_1.logger.warning('\nAmbiente: desarrollo');
72
+ }
73
+ }
74
+ catch (error) {
75
+ const message = error instanceof Error ? error.message : 'Error desconocido al actualizar el portal';
76
+ logger_1.logger.error(message);
77
+ process.exit(1);
78
+ }
79
+ });
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deleteWebhookCommand = void 0;
4
+ const commander_1 = require("commander");
5
+ const plazbot_1 = require("plazbot");
6
+ const credentials_1 = require("../../utils/credentials");
7
+ const logger_1 = require("../../utils/logger");
8
+ exports.deleteWebhookCommand = new commander_1.Command('delete-webhook')
9
+ .description('Elimina el webhook de WhatsApp')
10
+ .requiredOption('-n, --number <phone>', 'Número de WhatsApp (con código de país, ej: 51912345678)')
11
+ .option('--dev', 'Usar ambiente de desarrollo', false)
12
+ .action(async (options) => {
13
+ try {
14
+ const credentials = await (0, credentials_1.getStoredCredentials)();
15
+ const messageClient = new plazbot_1.Message({
16
+ workspaceId: credentials.workspace,
17
+ apiKey: credentials.apiKey,
18
+ zone: credentials.zone,
19
+ ...(options.dev && { customUrl: "http://localhost:5090" })
20
+ });
21
+ logger_1.logger.info('\n🗑️ Eliminando webhook de WhatsApp...');
22
+ logger_1.logger.info(`Número: ${options.number}`);
23
+ await messageClient.deleteWebhook({
24
+ number: options.number
25
+ });
26
+ logger_1.logger.success('Webhook eliminado exitosamente');
27
+ }
28
+ catch (error) {
29
+ logger_1.logger.error(`❌ Error al eliminar webhook: ${error.message}`);
30
+ process.exit(1);
31
+ }
32
+ });
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.whatsappCommands = void 0;
4
+ const commander_1 = require("commander");
5
+ const send_1 = require("./send");
6
+ const send_template_1 = require("./send-template");
7
+ const register_webhook_1 = require("./register-webhook");
8
+ const delete_webhook_1 = require("./delete-webhook");
9
+ exports.whatsappCommands = new commander_1.Command('whatsapp')
10
+ .description('Comandos relacionados con mensajes de WhatsApp')
11
+ .addCommand(send_1.sendMessageCommand)
12
+ .addCommand(send_template_1.sendTemplateCommand)
13
+ .addCommand(register_webhook_1.registerWebhookCommand)
14
+ .addCommand(delete_webhook_1.deleteWebhookCommand);
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerWebhookCommand = void 0;
4
+ const commander_1 = require("commander");
5
+ const plazbot_1 = require("plazbot");
6
+ const credentials_1 = require("../../utils/credentials");
7
+ const logger_1 = require("../../utils/logger");
8
+ exports.registerWebhookCommand = new commander_1.Command('register-webhook')
9
+ .description('Registra un webhook para WhatsApp')
10
+ .requiredOption('-n, --number <phone>', 'Número de WhatsApp (con código de país, ej: 51912345678)')
11
+ .requiredOption('-u, --url <webhook>', 'URL del webhook')
12
+ .option('--dev', 'Usar ambiente de desarrollo', false)
13
+ .action(async (options) => {
14
+ try {
15
+ const credentials = await (0, credentials_1.getStoredCredentials)();
16
+ const messageClient = new plazbot_1.Message({
17
+ workspaceId: credentials.workspace,
18
+ apiKey: credentials.apiKey,
19
+ zone: credentials.zone,
20
+ ...(options.dev && { customUrl: "http://localhost:5090" })
21
+ });
22
+ logger_1.logger.info('\n🔗 Registrando webhook de WhatsApp...');
23
+ logger_1.logger.info(`Número: ${options.number}`);
24
+ logger_1.logger.info(`URL: ${options.url}`);
25
+ await messageClient.registerWebhook({
26
+ number: options.number,
27
+ webhookUrl: options.url
28
+ });
29
+ logger_1.logger.success('Webhook registrado exitosamente');
30
+ }
31
+ catch (error) {
32
+ logger_1.logger.error(`❌ Error al registrar webhook: ${error.message}`);
33
+ process.exit(1);
34
+ }
35
+ });
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sendTemplateCommand = void 0;
4
+ const commander_1 = require("commander");
5
+ const plazbot_1 = require("plazbot");
6
+ const credentials_1 = require("../../utils/credentials");
7
+ const logger_1 = require("../../utils/logger");
8
+ exports.sendTemplateCommand = new commander_1.Command('send-template')
9
+ .description('Envía una plantilla de WhatsApp')
10
+ .requiredOption('-p, --phone <number>', 'Número de teléfono del destinatario (con código de país, ej: 51912345678)')
11
+ .requiredOption('-t, --template <name>', 'Nombre de la plantilla a enviar')
12
+ .option('--dev', 'Usar ambiente de desarrollo', false)
13
+ .action(async (options) => {
14
+ try {
15
+ const credentials = await (0, credentials_1.getStoredCredentials)();
16
+ const messageClient = new plazbot_1.Message({
17
+ workspaceId: credentials.workspace,
18
+ apiKey: credentials.apiKey,
19
+ zone: credentials.zone,
20
+ ...(options.dev && { customUrl: "http://localhost:5090" })
21
+ });
22
+ logger_1.logger.info('\n📱 Enviando plantilla de WhatsApp...');
23
+ logger_1.logger.info(`A: ${options.phone}`);
24
+ logger_1.logger.info(`Plantilla: ${options.template}`);
25
+ const response = await messageClient.onConversation({
26
+ to: options.phone,
27
+ template: options.template
28
+ });
29
+ logger_1.logger.success('Plantilla enviada exitosamente');
30
+ logger_1.logger.info('\n📋 Detalles:');
31
+ logger_1.logger.info(JSON.stringify(response, null, 2));
32
+ if (options.dev) {
33
+ logger_1.logger.warning('\nAmbiente: desarrollo');
34
+ }
35
+ }
36
+ catch (error) {
37
+ const message = error instanceof Error ? error.message : 'Error desconocido al enviar la plantilla';
38
+ logger_1.logger.error(message);
39
+ process.exit(1);
40
+ }
41
+ });
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sendMessageCommand = void 0;
4
+ const commander_1 = require("commander");
5
+ const plazbot_1 = require("plazbot");
6
+ const credentials_1 = require("../../utils/credentials");
7
+ const logger_1 = require("../../utils/logger");
8
+ exports.sendMessageCommand = new commander_1.Command('send-message')
9
+ .description('Envía un mensaje de WhatsApp')
10
+ .requiredOption('-t, --to <phone>', 'Número de teléfono del destinatario (con código de país, ej: 51912345678)')
11
+ .requiredOption('-m, --message <text>', 'Mensaje a enviar')
12
+ .option('--dev', 'Usar ambiente de desarrollo', false)
13
+ .action(async (options) => {
14
+ try {
15
+ // Obtener credenciales guardadas
16
+ const credentials = await (0, credentials_1.getStoredCredentials)();
17
+ const messageClient = new plazbot_1.Message({
18
+ workspaceId: credentials.workspace,
19
+ apiKey: credentials.apiKey,
20
+ zone: credentials.zone,
21
+ ...(options.dev && { customUrl: "http://localhost:5090" })
22
+ });
23
+ logger_1.logger.info('\n📱 Enviando mensaje de WhatsApp...');
24
+ logger_1.logger.info(`A: ${options.to}`);
25
+ logger_1.logger.info(`Mensaje: ${options.message}`);
26
+ const response = await messageClient.onWhatsappMessage({
27
+ message: options.message,
28
+ to: options.to
29
+ });
30
+ logger_1.logger.success('Mensaje enviado exitosamente');
31
+ logger_1.logger.info('\n📋 Detalles:');
32
+ logger_1.logger.info(JSON.stringify(response, null, 2));
33
+ if (options.dev) {
34
+ logger_1.logger.warning('\nAmbiente: desarrollo');
35
+ }
36
+ }
37
+ catch (error) {
38
+ const message = error?.message || 'Error desconocido al enviar el mensaje';
39
+ logger_1.logger.error(message);
40
+ process.exit(1);
41
+ }
42
+ });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getStoredCredentials = getStoredCredentials;
7
+ exports.saveCredentials = saveCredentials;
8
+ exports.removeCredentials = removeCredentials;
9
+ const promises_1 = __importDefault(require("fs/promises"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const os_1 = __importDefault(require("os"));
12
+ const configDir = path_1.default.join(os_1.default.homedir(), '.plazbot');
13
+ const configPath = path_1.default.join(configDir, 'config.json');
14
+ async function getStoredCredentials() {
15
+ try {
16
+ const configRaw = await promises_1.default.readFile(configPath, 'utf-8');
17
+ const config = JSON.parse(configRaw);
18
+ if (!config.apiKey || !config.workspace || !config.zone) {
19
+ throw new Error('Credenciales incompletas');
20
+ }
21
+ return config;
22
+ }
23
+ catch (error) {
24
+ throw new Error("No se encontró una sesión activa. Ejecuta 'plazbot init' primero.");
25
+ }
26
+ }
27
+ async function saveCredentials(credentials) {
28
+ await promises_1.default.mkdir(configDir, { recursive: true });
29
+ await promises_1.default.writeFile(configPath, JSON.stringify(credentials, null, 2));
30
+ }
31
+ async function removeCredentials() {
32
+ await promises_1.default.rm(configPath, { force: true });
33
+ }
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.logger = void 0;
4
+ exports.logger = {
5
+ info: (message) => {
6
+ console.log(message);
7
+ },
8
+ success: (message) => {
9
+ console.log(`\n✅ ${message}`);
10
+ },
11
+ warning: (message) => {
12
+ console.log(`\n⚠️ ${message}`);
13
+ },
14
+ error: (error) => {
15
+ const message = error instanceof Error ? error.message : error;
16
+ console.error(`\n❌ Error: ${message}`);
17
+ },
18
+ divider: (length = 50) => {
19
+ console.log('─'.repeat(length));
20
+ },
21
+ doubleDivider: (length = 50) => {
22
+ console.log('═'.repeat(length));
23
+ }
24
+ };
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "plazbot-cli",
3
+ "version": "0.1.2",
4
+ "description": "CLI para Plazbot SDK",
5
+ "main": "dist/cli.js",
6
+ "bin": {
7
+ "plazbot": "dist/cli.js"
8
+ },
9
+ "scripts": {
10
+ "build": "tsc",
11
+ "start": "node dist/cli.js",
12
+ "dev": "tsc -w",
13
+ "prepare:dev": "npm uninstall plazbot && npm install file:../Plazbot-SDK-v2.0",
14
+ "prepare:prod": "npm uninstall plazbot && npm install plazbot@latest",
15
+ "prepublishOnly": "npm run prepare:prod && npm run build",
16
+ "publish:beta": "npm publish --tag beta",
17
+ "publish:prod": "npm publish",
18
+ "version:patch": "npm version patch",
19
+ "version:minor": "npm version minor",
20
+ "version:major": "npm version major"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/tu-usuario/plazbot-cli.git"
25
+ },
26
+ "keywords": [
27
+ "plazbot",
28
+ "cli",
29
+ "sdk"
30
+ ],
31
+ "author": "Kristian Garcia <kristian@plazbot.com>",
32
+ "license": "MIT",
33
+ "dependencies": {
34
+ "@types/inquirer": "^9.0.8",
35
+ "axios": "^1.6.0",
36
+ "commander": "^12.0.0",
37
+ "inquirer": "^12.6.3",
38
+ "plazbot": "^1.1.3"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^20.0.0",
42
+ "typescript": "^5.0.0"
43
+ },
44
+ "engines": {
45
+ "node": ">=16.0.0"
46
+ }
47
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ import { program } from 'commander';
3
+ import { portalCommands } from './commands/portal';
4
+ import { authCommands } from './commands/auth';
5
+ import { agentCommands } from './commands/agent';
6
+ import { whatsappCommands } from './commands/whatsapp';
7
+
8
+ // Configuración básica del CLI
9
+ program
10
+ .name('plazbot')
11
+ .description('CLI para manejar agentes Plazbot')
12
+ .version('0.1.0');
13
+
14
+ // Registrar todos los comandos de autenticación
15
+ authCommands.forEach(cmd => program.addCommand(cmd));
16
+
17
+ // Registrar todos los comandos de agente
18
+ program.addCommand(agentCommands);
19
+
20
+ // Registrar todos los comandos de portal
21
+ program.addCommand(portalCommands);
22
+
23
+ // Registrar todos los comandos de WhatsApp
24
+ program.addCommand(whatsappCommands);
25
+
26
+ program.parse(process.argv);
@@ -0,0 +1,103 @@
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
+ import readline from 'readline';
8
+
9
+ export const chatCommand = new Command('chat')
10
+ .description('Inicia una sesión de chat interactiva con un agente')
11
+ .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)
14
+ .option('--dev', 'Usar ambiente de desarrollo', false)
15
+ .action(async (options: AgentCommandOptions & {
16
+ agentId: string;
17
+ sessionId?: string;
18
+ multipleAnswers?: boolean;
19
+ }) => {
20
+ try {
21
+ // Obtener credenciales guardadas
22
+ const credentials = await getStoredCredentials();
23
+
24
+ const agent = new Agent({
25
+ workspaceId: credentials.workspace,
26
+ apiKey: credentials.apiKey,
27
+ zone: credentials.zone,
28
+ ...(options.dev && { customUrl: "http://localhost:5090" })
29
+ });
30
+
31
+ // Generar un sessionId si no se proporcionó uno
32
+ const sessionId = options.sessionId || crypto.randomUUID();
33
+
34
+ // Crear interfaz de readline
35
+ const rl = readline.createInterface({
36
+ input: process.stdin,
37
+ output: process.stdout
38
+ });
39
+
40
+ // Limpiar la pantalla
41
+ console.clear();
42
+
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
+ const askQuestion = () => {
55
+ rl.question('You: ', async (question) => {
56
+ if (question.toLowerCase() === '/exit') {
57
+ console.log('\nChat session ended.');
58
+ rl.close();
59
+ return;
60
+ }
61
+
62
+ try {
63
+ console.log('⋮ Waiting for response...');
64
+
65
+ const response = await agent.onMessage({
66
+ agentId: options.agentId,
67
+ question,
68
+ sessionId,
69
+ multipleAnswers: options.multipleAnswers
70
+ }) as AgentResponse;
71
+
72
+ console.log('\nAssistant:');
73
+ console.log(' ' + response.answer);
74
+ console.log(); // Línea en blanco para separar mensajes
75
+
76
+ // Si hay fuentes, mostrarlas
77
+ if (response.sources && response.sources.length > 0) {
78
+ console.log('Sources:');
79
+ response.sources.forEach((source: AgentSource) => {
80
+ console.log(` - ${source.title || 'Untitled'}`);
81
+ if (source.url) console.log(` ${source.url}`);
82
+ });
83
+ console.log(); // Línea en blanco después de las fuentes
84
+ }
85
+
86
+ askQuestion(); // Continuar el ciclo de preguntas
87
+ } catch (error) {
88
+ const message = error instanceof Error ? error.message : 'Error desconocido';
89
+ console.error('\n❌ Error:', message);
90
+ askQuestion(); // Continuar a pesar del error
91
+ }
92
+ });
93
+ };
94
+
95
+ // Iniciar el ciclo de preguntas
96
+ askQuestion();
97
+
98
+ } catch (error) {
99
+ const message = error instanceof Error ? error.message : 'Error desconocido';
100
+ console.error('\n❌ Error:', message);
101
+ process.exit(1);
102
+ }
103
+ });
@@ -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 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
+ .option('--dev', 'Usar ambiente de desarrollo', false)
12
+ .action(async (configPath: string, options: AgentCommandOptions) => {
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
+ // 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}`);
32
+ }
33
+
34
+ logger.info('\n🤖 Creando nuevo agente...');
35
+ logger.info('Configuración:');
36
+ logger.info(JSON.stringify(agentConfig, null, 2));
37
+
38
+ const result = await agent.addAgent(agentConfig);
39
+
40
+ logger.success('Agente creado exitosamente');
41
+ logger.info('\n📋 Detalles del agente:');
42
+ logger.info(JSON.stringify(result, null, 2));
43
+
44
+ if (options.dev) {
45
+ logger.warning('\nAmbiente: desarrollo');
46
+ }
47
+
48
+ } catch (error) {
49
+ const message = error instanceof Error ? error.message : 'Error desconocido al crear el agente';
50
+ logger.error(message);
51
+ process.exit(1);
52
+ }
53
+ });
@@ -0,0 +1,64 @@
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 readline from 'readline';
7
+
8
+ export const deleteCommand = new Command('delete')
9
+ .description('Elimina un agente existente')
10
+ .argument('<agentId>', 'ID del agente a eliminar')
11
+ .option('--dev', 'Usar ambiente de desarrollo', false)
12
+ .action(async (agentId: string, options: AgentCommandOptions) => {
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 detalles del agente para mostrar información
25
+ const agentDetails = await agent.getAgentById({ id: agentId });
26
+
27
+ logger.warning('\nVas a eliminar el siguiente agente:');
28
+ logger.divider();
29
+ logger.info(`ID: ${agentDetails.agent.id}`);
30
+ logger.info(`Nombre: ${agentDetails.agent.name}`);
31
+ logger.info(`Descripción: ${agentDetails.agent.description}`);
32
+ logger.divider();
33
+
34
+ // Crear interfaz para confirmación
35
+ const rl = readline.createInterface({
36
+ input: process.stdin,
37
+ output: process.stdout
38
+ });
39
+
40
+ // Preguntar por confirmación
41
+ rl.question('\n❗ ¿Estás seguro que deseas eliminar este agente? (y/N): ', async (answer) => {
42
+ if (answer.toLowerCase() === 'y') {
43
+ await agent.deleteAgent({
44
+ id: agentId
45
+ });
46
+
47
+ logger.success('Agente eliminado exitosamente');
48
+
49
+ if (options.dev) {
50
+ logger.warning('Ambiente: desarrollo');
51
+ }
52
+ } else {
53
+ logger.error('Operación cancelada');
54
+ }
55
+
56
+ rl.close();
57
+ });
58
+
59
+ } catch (error) {
60
+ const message = error instanceof Error ? error.message : 'Error desconocido al eliminar el agente';
61
+ logger.error(message);
62
+ process.exit(1);
63
+ }
64
+ });