plazbot-cli
Version:
CLI para Plazbot SDK
168 lines (152 loc) • 7.18 kB
text/typescript
import { Command } from 'commander';
import { Agent } from 'plazbot';
import inquirer from 'inquirer';
import { getStoredCredentials } from '../../utils/credentials';
import { logger } from '../../utils/logger';
import { createSpinner, createTable, theme, section, kvPair, statusBadge } from '../../utils/ui';
import { AgentCommandOptions } from '../../types/agent';
export const toolsCommand = new Command('tools')
.description('Gestionar herramientas de Tool Calling del agente')
.argument('<agentId>', 'ID del agente')
.option('--dev', 'Usar ambiente de desarrollo', false)
.action(async (agentId: string, options: AgentCommandOptions) => {
try {
const credentials = await getStoredCredentials();
const agent = new Agent({
workspaceId: credentials.workspace,
apiKey: credentials.apiKey,
zone: credentials.zone,
...(options.dev && { customUrl: "http://localhost:5090" })
});
const spinner = createSpinner('Cargando agente...');
spinner.start();
const agentData = await agent.getAgentById({ id: agentId });
spinner.stop();
console.log(section('Tool Calling - ' + (agentData.name || agentId)));
console.log(kvPair('Estado', agentData.useToolCalling ? theme.success('Activado') : theme.error('Desactivado')));
// Servicios
const services = agentData.services || [];
if (services.length > 0) {
console.log(section('Servicios (API calls)'));
const rows = services.map((s: any) => [
s.intent,
s.method || 'POST',
s.endpoint ? s.endpoint.substring(0, 40) + '...' : 'N/A',
statusBadge(s.enabled !== false),
]);
console.log(createTable(['Intent', 'Method', 'Endpoint', 'Estado'], rows));
} else {
console.log(theme.muted('\n No hay servicios configurados'));
}
// Acciones
const actions = agentData.actions || [];
if (actions.length > 0) {
console.log(section('Acciones'));
const rows = actions.map((a: any) => [
a.intent,
(a.action || []).map((ac: any) => ac.type).join(', '),
statusBadge(a.enabled !== false),
]);
console.log(createTable(['Intent', 'Tipo', 'Estado'], rows));
} else {
console.log(theme.muted('\n No hay acciones configuradas'));
}
// Menu de opciones
console.log();
const { action } = await (inquirer as any).prompt([{
type: 'list',
name: 'action',
message: 'Que deseas hacer?',
choices: [
{ name: 'Agregar servicio (API call)', value: 'add-service' },
{ name: 'Agregar accion', value: 'add-action' },
{ name: agentData.useToolCalling ? 'Desactivar Tool Calling' : 'Activar Tool Calling', value: 'toggle' },
{ name: 'Salir', value: 'exit' },
],
}]);
if (action === 'exit') return;
if (action === 'toggle') {
const toggleSpinner = createSpinner('Actualizando...');
toggleSpinner.start();
const updatedConfig = { ...agentData, useToolCalling: !agentData.useToolCalling };
delete updatedConfig.id;
delete updatedConfig._id;
await agent.updateAgent(agentId, updatedConfig);
toggleSpinner.succeed(`Tool Calling ${!agentData.useToolCalling ? 'activado' : 'desactivado'}`);
return;
}
if (action === 'add-service') {
const svc = await (inquirer as any).prompt([
{ type: 'input', name: 'intent', message: 'Nombre/intent del servicio:', validate: (v: string) => v.length > 0 || 'Requerido' },
{ type: 'input', name: 'reference', message: 'Palabras clave:', default: '' },
{ type: 'list', name: 'method', message: 'Metodo HTTP:', choices: ['GET', 'POST'] },
{ type: 'input', name: 'endpoint', message: 'URL del endpoint:', validate: (v: string) => v.length > 0 || 'Requerido' },
{ type: 'input', name: 'responseMessage', message: 'Mensaje de respuesta:', default: '' },
]);
const newService = {
intent: svc.intent,
reference: svc.reference,
enabled: true,
method: svc.method,
endpoint: svc.endpoint,
requiredFields: [],
headers: {},
bodyTemplate: {},
responseMapping: {},
responseMessage: svc.responseMessage,
responseConditions: [],
};
const updatedServices = [...services, newService];
const updatedConfig = { ...agentData, services: updatedServices, useToolCalling: true };
delete updatedConfig.id;
delete updatedConfig._id;
const updateSpinner = createSpinner('Guardando servicio...');
updateSpinner.start();
await agent.updateAgent(agentId, updatedConfig);
updateSpinner.succeed(`Servicio "${svc.intent}" agregado`);
}
if (action === 'add-action') {
const act = await (inquirer as any).prompt([
{ type: 'input', name: 'intent', message: 'Nombre/intent de la accion:', validate: (v: string) => v.length > 0 || 'Requerido' },
{ type: 'input', name: 'reference', message: 'Palabras clave:', default: '' },
{
type: 'list', name: 'actionType', message: 'Tipo de accion:',
choices: [
{ name: 'Agendar evento', value: 'action.event.add' },
{ name: 'Actualizar evento (reagendar)', value: 'action.event.update' },
{ name: 'Listar eventos', value: 'action.event.list' },
{ name: 'Eliminar evento (cancelar)', value: 'action.event.delete' },
{ name: 'Agregar tag', value: 'action.tag' },
{ name: 'Cambiar stage', value: 'action.stage' },
{ name: 'Derivar a agente humano', value: 'action.agentShutDown' },
{ name: 'Marcar como resuelto', value: 'action.solved' },
{ name: 'Asignar agente', value: 'action.asign' },
{ name: 'Segmentacion', value: 'action.segmentation' },
],
},
{ type: 'input', name: 'actionValue', message: 'Valor (opcional):', default: '' },
{ type: 'input', name: 'responseMessage', message: 'Mensaje de respuesta:', default: '' },
]);
const newAction = {
intent: act.intent,
reference: act.reference,
enabled: true,
requiredFields: [],
responseMessage: act.responseMessage,
action: [{ type: act.actionType, value: act.actionValue }],
};
const updatedActions = [...actions, newAction];
const updatedConfig = { ...agentData, actions: updatedActions, useToolCalling: true };
delete updatedConfig.id;
delete updatedConfig._id;
const updateSpinner = createSpinner('Guardando accion...');
updateSpinner.start();
await agent.updateAgent(agentId, updatedConfig);
updateSpinner.succeed(`Accion "${act.intent}" agregada`);
}
} catch (error) {
const message = error instanceof Error ? error.message : 'Error desconocido';
logger.error(message);
process.exit(1);
}
});