npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

developer-holos-toolkit

v1.2.0

Published

Toolkit reutilizable con funciones de OpenAI Assistants y Kommo CRM para múltiples proyectos

Readme

developer-holos-toolkit

Toolkit reutilizable con funciones de OpenAI Assistants y Kommo CRM que uso en múltiples proyectos. Centraliza la funcionalidad común en una biblioteca NPM fácil de usar.

Nota: Este toolkit es una biblioteca de funciones reutilizables. Proyectos como OpenHome la consumen como dependencia.

🎯 Características

  • OpenAIService - Gestión completa de Assistants, Threads, Streaming y Tool Calls
  • KommoAuthService - Autenticación automática con refresh tokens
  • ThreadManager - Gestión simple de threads desechables (se almacenan en Kommo)
  • SchedulerService - Tareas programadas diarias o por intervalos
  • CLI Tools - Herramientas para migrar proyectos antiguos

📦 Instalación

npm install developer-holos-toolkit

🚀 Uso Rápido

OpenAI Service

const { OpenAIService } = require('developer-holos-toolkit');

// Inicializar servicio
const aiService = new OpenAIService({
  apiKey: process.env.OPENAI_API_KEY,
  assistantId: process.env.ASSISTANT_ID
});

// Registrar handlers para tool calls
aiService.registerToolHandler('obtener_datos_cliente', async (args, context) => {
  // Tu lógica específica aquí
  return { cliente: { id: args.id, nombre: 'Ejemplo' } };
});

// Procesar mensaje
const threadId = await aiService.createThread();
const response = await aiService.process(
  "Hola, necesito ayuda",
  threadId,
  null,
  { user_id: 12345 }
);

console.log(response);

Kommo Auth Service

const { KommoAuthService } = require('developer-holos-toolkit');
const Token = require('./models/Token'); // Tu modelo Sequelize

// Inicializar servicio
const kommoAuth = new KommoAuthService({
  domain: process.env.SUBDOMINIO,
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET,
  redirectUri: process.env.CLIENT_REDIRECT_URI,
  tokenModel: Token // Opcional, para persistencia en BD
});

// Autenticación automática
await kommoAuth.authenticate();

// Obtener token actual
const token = await kommoAuth.getToken();

// Hacer peticiones autenticadas
const account = await kommoAuth.request('GET', '/account');

Thread Manager

const { ThreadManager } = require('developer-holos-toolkit');

const manager = new ThreadManager();

// Crear thread para una conversación
// Los thread IDs son desechables y se almacenan en Kommo
// Cuando se borra en Kommo, se crea uno nuevo para la siguiente conversación
const threadId = await manager.create();

// Listar mensajes
const messages = await manager.listMessages(threadId);

Scheduler Service

const { SchedulerService } = require('developer-holos-toolkit');

const scheduler = new SchedulerService();

// Programar tarea diaria a las 2:00 AM
scheduler.scheduleDailyTask(
  'sincronizar-datos',
  async () => {
    console.log('Sincronizando datos...');
    // Tu lógica aquí
  },
  { hour: 2, minute: 0 }
);

// Ejecutar tarea manualmente
await scheduler.runTaskNow('sincronizar-datos');

// Ver tareas programadas
console.log(scheduler.listTasks());

🔧 CLI Tools

Migrar proyecto antiguo

npx dh-migrate --from ./old-project

Este comando analiza tu proyecto y te muestra cómo migrar a este toolkit.

Extraer servicio específico

# Ver lista de servicios
npx dh-extract

# Extraer servicio a archivo
npx dh-extract --service openai --output ./my-service.js

📚 Ejemplo de Migración

Antes:

const OpenAIService = require('./services/openaiService');
const { authenticate } = require('./services/refreshTokenKommo');

await authenticate();
const service = new OpenAIService();
const response = await service.main(message, threadId, leadId);

Después:

const { OpenAIService, KommoAuthService } = require('developer-holos-toolkit');

const kommo = new KommoAuthService();
await kommo.authenticate();

const ai = new OpenAIService();
const response = await ai.process(message, threadId);

🏗️ Estructura del Proyecto

developer-holos-toolkit/
├── core/
│   ├── OpenAIService.js      # Servicio principal OpenAI
│   ├── KommoAuthService.js   # Autenticación Kommo
│   ├── ThreadManager.js      # Gestión de threads
│   └── SchedulerService.js   # Tareas programadas
├── utils/
│   └── openai-helpers.js     # Utilidades OpenAI
├── cli/
│   ├── migrate.js            # CLI de migración
│   └── extract.js            # CLI de extracción
├── index.js                  # Exportaciones principales
└── package.json

⚙️ Configuración

Crea un archivo .env:

# OpenAI
OPENAI_API_KEY=sk-...
ASSISTANT_ID=asst_...

# Kommo
SUBDOMINIO=tu-subdominio
CLIENT_ID=...
CLIENT_SECRET=...
CLIENT_REDIRECT_URI=...

# Base de datos (opcional)
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=...
DB_NAME=...

🔄 Actualizar proyectos antiguos

  1. Instala el framework: npm install developer-holos-toolkit
  2. Usa la CLI de migración: npx dh-migrate --from ./proyecto-viejo
  3. Reemplaza imports según las instrucciones
  4. Prueba que todo funcione
  5. Elimina archivos antiguos

📖 API Completa

OpenAIService

  • constructor(config) - Inicializa el servicio
  • registerToolHandler(name, handler) - Registra handler para tool call
  • createThread() - Crea nuevo thread
  • deleteThread(threadId) - Elimina thread
  • createMessage(threadId, content) - Crea mensaje
  • process(message, threadId, assistantId, context) - Procesa mensaje completo
  • runWithStreaming(threadId, assistantId, context) - Ejecuta con streaming
  • waitForActiveRunsToComplete(threadId) - Espera ejecuciones activas

KommoAuthService

  • constructor(config) - Inicializa el servicio
  • authenticate() - Autentica (verifica y refresca si necesario)
  • getToken() - Obtiene token actual
  • refreshToken() - Refresca token manualmente
  • verifyToken() - Verifica si token es válido
  • request(method, endpoint, data) - Petición autenticada a Kommo API

ThreadManager

  • constructor(config) - Inicializa el manager
  • create() - Crea un nuevo thread (desechable, se almacena en Kommo)
  • delete(threadId) - Elimina thread
  • listMessages(threadId, limit) - Lista mensajes del thread

SchedulerService

  • scheduleDailyTask(name, fn, options) - Programa tarea diaria
  • scheduleIntervalTask(name, fn, intervalMs) - Programa tarea por intervalo
  • runTaskNow(name) - Ejecuta tarea inmediatamente
  • stopTask(name) - Detiene tarea
  • stopAll() - Detiene todas las tareas
  • listTasks() - Lista tareas programadas
  • getTaskStatus(name) - Obtiene estado de tarea

💡 Casos de Uso

Chatbot con Kommo

const { OpenAIService, KommoAuthService, ThreadManager } = require('developer-holos-toolkit');

// Setup
const kommo = new KommoAuthService({ tokenModel: Token });
const ai = new OpenAIService();
const threads = new ThreadManager();

// Handler para actualizar lead en Kommo
ai.registerToolHandler('actualizar_lead', async (args, context) => {
  const { lead_id } = context;
  await kommo.request('PATCH', `/leads/${lead_id}`, args);
  return { success: true };
});

// Procesar mensaje
app.post('/webhook/message', async (req, res) => {
  const { lead_id, message, thread_id } = req.body;
  
  await kommo.authenticate();
  
  // Si no hay thread_id (nueva conversación), crear uno nuevo
  // El thread_id se almacena en Kommo y es desechable
  let threadId = thread_id;
  if (!threadId) {
    threadId = await threads.create();
    // Guardar threadId en Kommo aquí
  }
  
  const response = await ai.process(message, threadId, null, { lead_id });
  
  res.json({ response, thread_id: threadId });
});

Sistema de actualizaciones programadas

const { SchedulerService } = require('developer-holos-toolkit');

const scheduler = new SchedulerService();

// Sincronizar con API externa cada 6 horas
scheduler.scheduleIntervalTask(
  'sync-external-api',
  async () => {
    const data = await fetchExternalAPI();
    await syncToDatabase(data);
  },
  6 * 60 * 60 * 1000
);

// Reporte diario a las 9 AM
scheduler.scheduleDailyTask(
  'daily-report',
  async () => {
    const report = await generateReport();
    await sendEmailReport(report);
  },
  { hour: 9, minute: 0 }
);

🤝 Contribuciones

Este framework está diseñado para proyectos de Developer-Holos. Si encuentras bugs o tienes sugerencias, abre un issue.

📄 Licencia

MIT © Developer-Holos