@johpaz/hive-agents 0.0.8 → 0.0.11

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.
package/dist/hive.js CHANGED
@@ -16054,7 +16054,7 @@ var SCHEMA = `
16054
16054
  description TEXT,
16055
16055
  category TEXT,
16056
16056
  enabled INTEGER NOT NULL DEFAULT 1,
16057
- active INTEGER NOT NULL DEFAULT 0,
16057
+ active INTEGER NOT NULL DEFAULT 1,
16058
16058
  created_at INTEGER NOT NULL DEFAULT (unixepoch()),
16059
16059
  updated_at INTEGER NOT NULL DEFAULT (unixepoch())
16060
16060
  );
@@ -16441,6 +16441,21 @@ var SCHEMA = `
16441
16441
  -- Simplified schema - standalone FTS5 table (no content table sync)
16442
16442
  -- Note: FTS5 tables are created programmatically in seed.ts to avoid "already exists" errors
16443
16443
 
16444
+ -- REFRESH TOKENS: JWT refresh token storage (hash-based for security)
16445
+ -- Stores hashed refresh tokens with expiry and user linkage
16446
+ CREATE TABLE IF NOT EXISTS refresh_tokens (
16447
+ id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
16448
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
16449
+ token_hash TEXT NOT NULL UNIQUE,
16450
+ expires_at INTEGER NOT NULL,
16451
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
16452
+ revoked INTEGER NOT NULL DEFAULT 0
16453
+ );
16454
+
16455
+ CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user ON refresh_tokens(user_id);
16456
+ CREATE INDEX IF NOT EXISTS idx_refresh_tokens_hash ON refresh_tokens(token_hash);
16457
+ CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires ON refresh_tokens(expires_at);
16458
+
16444
16459
  -- Agent Bus: Message queue for worker-to-worker communication
16445
16460
  CREATE TABLE IF NOT EXISTS agent_bus_messages (
16446
16461
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -19814,83 +19829,90 @@ var init_seed = __esm(() => {
19814
19829
  init_src();
19815
19830
  SEED_DATA = {
19816
19831
  tools: [
19817
- { id: "fs_read", name: "fs_read", category: "filesystem", description: "Read file content from agent workspace. Spanish: leer archivo, ver contenido, abrir archivo" },
19818
- { id: "fs_write", name: "fs_write", category: "filesystem", description: "Create or overwrite file in agent workspace. Spanish: crear archivo, guardar archivo, escribir archivo" },
19819
- { id: "fs_edit", name: "fs_edit", category: "filesystem", description: "Edit specific lines or sections of a file. Spanish: editar archivo, modificar l\xEDneas, actualizar contenido" },
19820
- { id: "fs_delete", name: "fs_delete", category: "filesystem", description: "Delete file or directory from workspace. Spanish: eliminar archivo, borrar archivo, borrar carpeta" },
19821
- { id: "fs_list", name: "fs_list", category: "filesystem", description: "List files and directories in workspace. Spanish: listar archivos, ver carpeta, explorar directorio" },
19822
- { id: "fs_glob", name: "fs_glob", category: "filesystem", description: "Find files matching wildcard patterns. Spanish: buscar archivos, patr\xF3n, encontrar archivos" },
19823
- { id: "fs_exists", name: "fs_exists", category: "filesystem", description: "Check if a file or directory exists. Spanish: verificar archivo, comprobar, existe archivo" },
19824
- { id: "web_search", name: "web_search", category: "web", description: "Search the web for current information and research. Spanish: buscar en internet, b\xFAsqueda web, noticias, informaci\xF3n" },
19825
- { id: "web_fetch", name: "web_fetch", category: "web", description: "Fetch plain content from a URL (lightweight, no JS). Spanish: obtener p\xE1gina, descargar contenido, extraer texto de url" },
19826
- { id: "browser_navigate", name: "browser_navigate", category: "web", description: "Navigate browser to URL, get rendered page content (supports JS). Spanish: navegar a url, abrir p\xE1gina, sitio web" },
19827
- { id: "browser_screenshot", name: "browser_screenshot", category: "web", description: "Take screenshot of current browser page. Spanish: captura de pantalla, screenshot, imagen de p\xE1gina" },
19828
- { id: "browser_click", name: "browser_click", category: "web", description: "Click on a web page element. Spanish: hacer clic, bot\xF3n, enlace, interactuar" },
19829
- { id: "browser_type", name: "browser_type", category: "web", description: "Type text into a form field in the browser. Spanish: escribir formulario, tipear, campo de texto, input" },
19830
- { id: "browser_extract", name: "browser_extract", category: "web", description: "Extract text, links, or structured data from page using CSS selectors or XPath. Spanish: extraer datos, obtener informaci\xF3n, scraping, selectores" },
19831
- { id: "browser_script", name: "browser_script", category: "web", description: "Execute arbitrary JavaScript in the browser page context and get the result. Spanish: ejecutar javascript, script, c\xF3digo, funci\xF3n, evaluar" },
19832
- { id: "browser_wait", name: "browser_wait", category: "web", description: "Wait for an element to appear or condition to be met on the page. Spanish: esperar, wait, condici\xF3n, elemento, selector" },
19833
- { id: "project_create", name: "project_create", category: "projects", description: "Create a new project with tasks in the database. Spanish: crear proyecto, nuevo proyecto, iniciar plan" },
19834
- { id: "project_list", name: "project_list", category: "projects", description: "List all projects with their status. Spanish: listar proyectos, ver proyectos, historial" },
19835
- { id: "project_update", name: "project_update", category: "projects", description: "Update project progress or metadata. Spanish: actualizar proyecto, avance, porcentaje, estado" },
19836
- { id: "project_done", name: "project_done", category: "projects", description: "Mark project as completed and archive it. Spanish: proyecto terminado, cerrar proyecto, completado" },
19837
- { id: "project_fail", name: "project_fail", category: "projects", description: "Mark project as failed and record reason. Spanish: proyecto fallido, marcar fracaso, error" },
19838
- { id: "task_create", name: "task_create", category: "projects", description: "Add a task or subtask to an existing project. Spanish: crear tarea, agregar tarea, subtarea, pendiente" },
19839
- { id: "task_update", name: "task_update", category: "projects", description: "Update task status (pending, in_progress, done). Spanish: actualizar tarea, marcar completa, en progreso" },
19840
- { id: "task_evaluate", name: "task_evaluate", category: "projects", description: "Evaluate task result against acceptance criteria. Spanish: evaluar tarea, validar resultado, criterios de aceptaci\xF3n" },
19841
- { id: "hive.schedule.create", name: "hive.schedule.create", category: "schedule", description: "Create new scheduled task: recurring (cron expression) or one-shot (fire_at). Spanish: programar tarea, crear recordatorio, agendar, automatizar horario, tarea recurrente, una vez" },
19842
- { id: "hive.schedule.list", name: "hive.schedule.list", category: "schedule", description: "List all scheduled tasks with next execution times and status. Spanish: ver tareas programadas, listar cronograma, pr\xF3ximas ejecuciones" },
19843
- { id: "hive.schedule.pause", name: "hive.schedule.pause", category: "schedule", description: "Pause a scheduled task temporarily without deleting it. Spanish: pausar tarea programada, detener temporalmente, suspender recordatorio" },
19844
- { id: "hive.schedule.resume", name: "hive.schedule.resume", category: "schedule", description: "Resume a previously paused scheduled task. Spanish: reanudar tarea, continuar tarea pausada, activar recordatorio" },
19845
- { id: "hive.schedule.delete", name: "hive.schedule.delete", category: "schedule", description: "Delete a scheduled task permanently. Spanish: eliminar tarea programada, borrar recordatorio, cancelar tarea" },
19846
- { id: "hive.schedule.trigger", name: "hive.schedule.trigger", category: "schedule", description: "Manually trigger immediate execution of a scheduled task. Spanish: ejecutar tarea ahora, forzar ejecuci\xF3n, disparar manualmente" },
19847
- { id: "hive.schedule.history", name: "hive.schedule.history", category: "schedule", description: "Get execution history and run logs for a scheduled task. Spanish: historial ejecuciones, logs tarea, registro ejecuciones" },
19848
- { id: "cli_exec", name: "cli_exec", category: "cli", description: "Execute shell/bash commands in the agent environment. NOTE: do NOT use for scheduling tasks, use hive.schedule.create instead. Spanish: ejecutar comando, terminal, bash, script, consola" },
19849
- { id: "memory_write", name: "memory_write", category: "agents", description: "Store information in persistent long-term memory. Spanish: guardar memoria, recordar, guardar dato, memoria persistente" },
19850
- { id: "memory_read", name: "memory_read", category: "agents", description: "Retrieve a memory entry by identifier. Spanish: leer memoria, recuperar dato, obtener memoria" },
19851
- { id: "memory_list", name: "memory_list", category: "agents", description: "List all saved memory entries. Spanish: listar memorias, ver memorias, todas las memorias" },
19852
- { id: "memory_search", name: "memory_search", category: "agents", description: "Search memories by keyword. Spanish: buscar memoria, encontrar recuerdo, buscar dato guardado" },
19853
- { id: "memory_delete", name: "memory_delete", category: "agents", description: "Delete a specific memory entry. Spanish: borrar memoria, eliminar recuerdo, quitar dato" },
19854
- { id: "agent_create", name: "agent_create", category: "agents", description: "Create a new specialized worker agent. Spanish: crear agente, nuevo worker, nuevo trabajador" },
19855
- { id: "agent_find", name: "agent_find", category: "agents", description: "Find existing running or idle worker agents. Spanish: buscar agente, encontrar worker, localizar agente" },
19856
- { id: "agent_archive", name: "agent_archive", category: "agents", description: "Archive or terminate a worker agent. Spanish: archivar agente, terminar worker, desactivar agente" },
19857
- { id: "task_delegate", name: "task_delegate", category: "agents", description: "Delegate a general task to a specific worker agent. Spanish: delegar tarea, asignar worker, ejecutar por agente" },
19858
- { id: "task_delegate_code", name: "task_delegate_code", category: "agents", description: "Delegate a coding task to a CLI subagent (Qwen, Claude, etc.) via Code Bridge. Spanish: delegar c\xF3digo, subagente CLI, programaci\xF3n, Qwen" },
19859
- { id: "task_status", name: "task_status", category: "agents", description: "Get execution status of one or more delegated tasks. Spanish: estado tarea delegada, verificar progreso, consultar tarea" },
19860
- { id: "bus_publish", name: "bus_publish", category: "agents", description: "Publish a message to the Agent Bus for worker-to-worker communication. Spanish: publicar mensaje, comunicar workers, enviar bus" },
19861
- { id: "bus_read", name: "bus_read", category: "agents", description: "Read unread messages from the Agent Bus. Spanish: leer mensajes bus, recibir mensajes, verificar bus" },
19862
- { id: "project_updates", name: "project_updates", category: "agents", description: "Get recent status updates from workers in the same project. Spanish: actualizaciones proyecto, estado workers, progreso equipo" },
19863
- { id: "canvas_render", name: "canvas_render", category: "canvas", description: "Render a component or visualization on the canvas. Spanish: renderizar, visualizar, gr\xE1fico, diagrama" },
19864
- { id: "canvas_ask", name: "canvas_ask", category: "canvas", description: "Show interactive form and wait for user input. Spanish: formulario interactivo, preguntar usuario, input" },
19865
- { id: "canvas_confirm", name: "canvas_confirm", category: "canvas", description: "Show a confirmation dialog before executing an action. Spanish: confirmar acci\xF3n, di\xE1logo, aprobar" },
19866
- { id: "canvas_show_card", name: "canvas_show_card", category: "canvas", description: "Display structured information in card format. Spanish: mostrar tarjeta, card, informaci\xF3n estructurada" },
19867
- { id: "canvas_show_progress", name: "canvas_show_progress", category: "canvas", description: "Show progress bar or status indicator. Spanish: barra de progreso, indicador, progreso visual" },
19868
- { id: "canvas_show_list", name: "canvas_show_list", category: "canvas", description: "Display key-value list information. Spanish: lista clave-valor, mostrar lista, informaci\xF3n en lista" },
19869
- { id: "canvas_clear", name: "canvas_clear", category: "canvas", description: "Clear current canvas content. Spanish: limpiar canvas, borrar visualizaci\xF3n, resetear" },
19832
+ { id: "fs_read", name: "fs_read", category: "filesystem", description: "Leer contenido de archivos del espacio de trabajo. Sin\xF3nimos: ver archivo, abrir archivo, leer contenido, mostrar archivo" },
19833
+ { id: "fs_write", name: "fs_write", category: "filesystem", description: "Crear o sobrescribir archivos en el espacio de trabajo. Sin\xF3nimos: crear archivo, guardar archivo, escribir archivo, nuevo archivo" },
19834
+ { id: "fs_edit", name: "fs_edit", category: "filesystem", description: "Editar l\xEDneas espec\xEDficas o secciones de un archivo. Sin\xF3nimos: modificar archivo, editar l\xEDneas, actualizar contenido, cambiar texto" },
19835
+ { id: "fs_delete", name: "fs_delete", category: "filesystem", description: "Eliminar archivos o directorios del espacio de trabajo. Sin\xF3nimos: borrar archivo, eliminar carpeta, quitar archivo, remover" },
19836
+ { id: "fs_list", name: "fs_list", category: "filesystem", description: "Listar archivos y directorios en el espacio de trabajo. Sin\xF3nimos: ver carpeta, explorar directorio, listar contenido, mostrar archivos" },
19837
+ { id: "fs_glob", name: "fs_glob", category: "filesystem", description: "Buscar archivos que coincidan con patrones wildcard. Sin\xF3nimos: buscar archivos, patr\xF3n, encontrar archivos, filtrar por nombre" },
19838
+ { id: "fs_exists", name: "fs_exists", category: "filesystem", description: "Verificar si existe un archivo o directorio. Sin\xF3nimos: comprobar archivo, existe archivo, verificar existencia, hay archivo" },
19839
+ { id: "web_search", name: "web_search", category: "web", description: "Buscar en la web informaci\xF3n actual y noticias. Sin\xF3nimos: b\xFAsqueda web, noticias, informaci\xF3n, buscar en internet, google" },
19840
+ { id: "web_fetch", name: "web_fetch", category: "web", description: "Obtener contenido de texto de una URL (ligero, sin JS). Sin\xF3nimos: descargar p\xE1gina, extraer texto, obtener contenido, leer url" },
19841
+ { id: "browser_navigate", name: "browser_navigate", category: "web", description: "Navegar a una URL y obtener contenido renderizado (soporta JS). Sin\xF3nimos: abrir p\xE1gina, sitio web, navegar url, cargar p\xE1gina" },
19842
+ { id: "browser_screenshot", name: "browser_screenshot", category: "web", description: "Tomar captura de pantalla de la p\xE1gina actual. Sin\xF3nimos: screenshot, imagen de p\xE1gina, capturar pantalla, foto p\xE1gina" },
19843
+ { id: "browser_click", name: "browser_click", category: "web", description: "Hacer clic en un elemento de la p\xE1gina web. Sin\xF3nimos: bot\xF3n, enlace, interactuar, presionar, seleccionar" },
19844
+ { id: "browser_type", name: "browser_type", category: "web", description: "Escribir texto en un campo de formulario. Sin\xF3nimos: escribir formulario, tipear, campo de texto, input, llenar campo" },
19845
+ { id: "browser_extract", name: "browser_extract", category: "web", description: "Extraer texto, enlaces o datos estructurados usando selectores CSS o XPath. Sin\xF3nimos: obtener datos, scraping, selectores, extraer informaci\xF3n" },
19846
+ { id: "browser_script", name: "browser_script", category: "web", description: "Ejecutar JavaScript arbitrario en el navegador y obtener resultado. Sin\xF3nimos: ejecutar javascript, script, c\xF3digo, funci\xF3n, evaluar" },
19847
+ { id: "browser_wait", name: "browser_wait", category: "web", description: "Esperar a que aparezca un elemento o se cumpla una condici\xF3n. Sin\xF3nimos: esperar, condici\xF3n, elemento, selector, pausa" },
19848
+ { id: "project_create", name: "project_create", category: "projects", description: "Crear un nuevo proyecto con tareas en la base de datos. Sin\xF3nimos: nuevo proyecto, iniciar plan, crear proyecto" },
19849
+ { id: "project_list", name: "project_list", category: "projects", description: "Listar todos los proyectos con su estado. Sin\xF3nimos: ver proyectos, historial, listar proyectos, mostrar proyectos" },
19850
+ { id: "project_update", name: "project_update", category: "projects", description: "Actualizar progreso o metadatos del proyecto. Sin\xF3nimos: avance, porcentaje, estado, actualizar proyecto" },
19851
+ { id: "project_done", name: "project_done", category: "projects", description: "Marcar proyecto como completado y archivarlo. Sin\xF3nimos: proyecto terminado, cerrar proyecto, completado, finalizar" },
19852
+ { id: "project_fail", name: "project_fail", category: "projects", description: "Marcar proyecto como fallido y registrar raz\xF3n. Sin\xF3nimos: proyecto fallido, marcar fracaso, error, fall\xF3 proyecto" },
19853
+ { id: "task_create", name: "task_create", category: "projects", description: "Agregar una tarea o subtarea a un proyecto existente. Sin\xF3nimos: crear tarea, agregar tarea, subtarea, pendiente" },
19854
+ { id: "task_update", name: "task_update", category: "projects", description: "Actualizar estado de tarea (pendiente, en_progreso, hecho). Sin\xF3nimos: actualizar tarea, marcar completa, en progreso" },
19855
+ { id: "task_evaluate", name: "task_evaluate", category: "projects", description: "Evaluar resultado de tarea contra criterios de aceptaci\xF3n. Sin\xF3nimos: validar resultado, criterios de aceptaci\xF3n, revisar tarea" },
19856
+ { id: "hive.schedule.create", name: "hive.schedule.create", category: "schedule", description: "Crear tarea programada: recurrente (expresi\xF3n cron) o \xFAnica (fire_at). Sin\xF3nimos: programar tarea, crear recordatorio, agendar, automatizar horario, tarea recurrente, una vez" },
19857
+ { id: "hive.schedule.list", name: "hive.schedule.list", category: "schedule", description: "Listar todas las tareas programadas con pr\xF3ximos horarios de ejecuci\xF3n. Sin\xF3nimos: ver tareas programadas, listar cronograma, pr\xF3ximas ejecuciones" },
19858
+ { id: "hive.schedule.pause", name: "hive.schedule.pause", category: "schedule", description: "Pausar temporalmente una tarea programada sin eliminarla. Sin\xF3nimos: pausar tarea programada, detener temporalmente, suspender recordatorio" },
19859
+ { id: "hive.schedule.resume", name: "hive.schedule.resume", category: "schedule", description: "Reanudar una tarea programada previamente pausada. Sin\xF3nimos: reanudar tarea, continuar tarea pausada, activar recordatorio" },
19860
+ { id: "hive.schedule.delete", name: "hive.schedule.delete", category: "schedule", description: "Eliminar una tarea programada permanentemente. Sin\xF3nimos: eliminar tarea programada, borrar recordatorio, cancelar tarea" },
19861
+ { id: "hive.schedule.trigger", name: "hive.schedule.trigger", category: "schedule", description: "Ejecutar manualmente una tarea programada de forma inmediata. Sin\xF3nimos: ejecutar tarea ahora, forzar ejecuci\xF3n, disparar manualmente" },
19862
+ { id: "hive.schedule.history", name: "hive.schedule.history", category: "schedule", description: "Obtener historial de ejecuciones y logs de una tarea programada. Sin\xF3nimos: historial ejecuciones, logs tarea, registro ejecuciones" },
19863
+ { id: "cli_exec", name: "cli_exec", category: "cli", description: "Ejecutar comandos shell/bash en el entorno del agente. NOTA: NO usar para tareas programadas, usar hive.schedule.create. Sin\xF3nimos: ejecutar comando, terminal, bash, script, consola" },
19864
+ { id: "memory_write", name: "memory_write", category: "agents", description: "Guardar informaci\xF3n en memoria persistente a largo plazo. Sin\xF3nimos: guardar memoria, recordar, guardar dato, memoria persistente" },
19865
+ { id: "memory_read", name: "memory_read", category: "agents", description: "Recuperar una entrada de memoria por identificador. Sin\xF3nimos: leer memoria, recuperar dato, obtener memoria" },
19866
+ { id: "memory_list", name: "memory_list", category: "agents", description: "Listar todas las entradas de memoria guardadas. Sin\xF3nimos: listar memorias, ver memorias, todas las memorias" },
19867
+ { id: "memory_search", name: "memory_search", category: "agents", description: "Buscar memorias por palabra clave. Sin\xF3nimos: buscar memoria, encontrar recuerdo, buscar dato guardado" },
19868
+ { id: "memory_delete", name: "memory_delete", category: "agents", description: "Eliminar una entrada de memoria espec\xEDfica. Sin\xF3nimos: borrar memoria, eliminar recuerdo, quitar dato" },
19869
+ { id: "get_available_models", name: "get_available_models", category: "agents", description: "Obtener lista de providers y modelos activos de la BD. Sin\xF3nimos: ver modelos, listar providers, modelos disponibles, consultar modelos, provider activo, qu\xE9 modelos tengo, modelos para c\xF3digo, modelos para chat" },
19870
+ { id: "agent_create", name: "agent_create", category: "agents", description: "Crear un nuevo agente worker especializado. Sin\xF3nimos: crear agente, nuevo worker, nuevo trabajador" },
19871
+ { id: "agent_find", name: "agent_find", category: "agents", description: "Buscar agentes worker existentes en ejecuci\xF3n o inactivos. Sin\xF3nimos: buscar agente, encontrar worker, localizar agente" },
19872
+ { id: "agent_archive", name: "agent_archive", category: "agents", description: "Archivar o terminar un agente worker. Sin\xF3nimos: archivar agente, terminar worker, desactivar agente" },
19873
+ { id: "task_delegate", name: "task_delegate", category: "agents", description: "Delegar una tarea general a un agente worker espec\xEDfico. Sin\xF3nimos: delegar tarea, asignar worker, ejecutar por agente" },
19874
+ { id: "task_delegate_code", name: "task_delegate_code", category: "agents", description: "Delegar tarea de c\xF3digo a un subagente CLI (Qwen, Claude, etc.) v\xEDa Code Bridge. Sin\xF3nimos: delegar c\xF3digo, subagente CLI, programaci\xF3n, Qwen" },
19875
+ { id: "task_status", name: "task_status", category: "agents", description: "Obtener estado de ejecuci\xF3n de tareas delegadas. Sin\xF3nimos: estado tarea delegada, verificar progreso, consultar tarea" },
19876
+ { id: "bus_publish", name: "bus_publish", category: "agents", description: "Publicar mensaje en el Agent Bus para comunicaci\xF3n worker-to-worker. Sin\xF3nimos: publicar mensaje, comunicar workers, enviar bus" },
19877
+ { id: "bus_read", name: "bus_read", category: "agents", description: "Leer mensajes no le\xEDdos del Agent Bus. Sin\xF3nimos: leer mensajes bus, recibir mensajes, verificar bus" },
19878
+ { id: "project_updates", name: "project_updates", category: "agents", description: "Obtener actualizaciones recientes de workers en el mismo proyecto. Sin\xF3nimos: actualizaciones proyecto, estado workers, progreso equipo" },
19879
+ { id: "canvas_render", name: "canvas_render", category: "canvas", description: "Renderizar un componente o visualizaci\xF3n en el canvas. Sin\xF3nimos: renderizar, visualizar, gr\xE1fico, diagrama" },
19880
+ { id: "canvas_ask", name: "canvas_ask", category: "canvas", description: "Mostrar formulario interactivo y esperar input del usuario. Sin\xF3nimos: formulario interactivo, preguntar usuario, input" },
19881
+ { id: "canvas_confirm", name: "canvas_confirm", category: "canvas", description: "Mostrar di\xE1logo de confirmaci\xF3n antes de ejecutar una acci\xF3n. Sin\xF3nimos: confirmar acci\xF3n, di\xE1logo, aprobar" },
19882
+ { id: "canvas_show_card", name: "canvas_show_card", category: "canvas", description: "Mostrar informaci\xF3n estructurada en formato de tarjeta. Sin\xF3nimos: mostrar tarjeta, card, informaci\xF3n estructurada" },
19883
+ { id: "canvas_show_progress", name: "canvas_show_progress", category: "canvas", description: "Mostrar barra de progreso o indicador de estado. Sin\xF3nimos: barra de progreso, indicador, progreso visual" },
19884
+ { id: "canvas_show_list", name: "canvas_show_list", category: "canvas", description: "Mostrar informaci\xF3n en lista clave-valor. Sin\xF3nimos: lista clave-valor, mostrar lista, informaci\xF3n en lista" },
19885
+ { id: "canvas_clear", name: "canvas_clear", category: "canvas", description: "Limpiar contenido actual del canvas. Sin\xF3nimos: limpiar canvas, borrar visualizaci\xF3n, resetear" },
19870
19886
  {
19871
19887
  id: "codebridge_launch",
19872
19888
  name: "codebridge_launch",
19873
19889
  category: "codebridge",
19874
- description: "Launch an external coding CLI subagent (Claude Code, Qwen CLI, Gemini CLI, OpenCode CLI) to execute a coding task locally. Returns a process ID to track execution. Spanish: lanzar agente de c\xF3digo, iniciar Claude Code, Qwen CLI, Gemini CLI, OpenCode, subagente externo de programaci\xF3n"
19890
+ description: "Lanzar un subagente externo de c\xF3digo (Claude Code, Qwen CLI, Gemini CLI, OpenCode) para ejecutar tarea localmente. Retorna ID de proceso para trackear. Sin\xF3nimos: lanzar agente de c\xF3digo, iniciar Claude Code, Qwen CLI, Gemini CLI, OpenCode, subagente externo de programaci\xF3n"
19875
19891
  },
19876
19892
  {
19877
19893
  id: "codebridge_status",
19878
19894
  name: "codebridge_status",
19879
19895
  category: "codebridge",
19880
- description: "Check the status and output of a running CodeBridge subagent (Claude Code, Qwen CLI, Gemini CLI, OpenCode CLI). Spanish: estado agente de c\xF3digo, verificar Claude Code, progreso subagente externo"
19896
+ description: "Verificar estado y salida de un subagente CodeBridge en ejecuci\xF3n. Sin\xF3nimos: estado agente de c\xF3digo, verificar Claude Code, progreso subagente externo"
19881
19897
  },
19882
19898
  {
19883
19899
  id: "codebridge_cancel",
19884
19900
  name: "codebridge_cancel",
19885
19901
  category: "codebridge",
19886
- description: "Cancel and terminate a running CodeBridge subagent process (Claude Code, Qwen CLI, Gemini CLI, OpenCode CLI). Spanish: cancelar agente de c\xF3digo, detener Claude Code, terminar subagente externo"
19902
+ description: "Cancelar y terminar un proceso de subagente CodeBridge en ejecuci\xF3n. Sin\xF3nimos: cancelar agente de c\xF3digo, detener Claude Code, terminar subagente externo"
19903
+ },
19904
+ {
19905
+ id: "codebridge_feedback",
19906
+ name: "codebridge_feedback",
19907
+ category: "codebridge",
19908
+ description: "Enviar feedback o instrucciones adicionales a un subagente CodeBridge en ejecuci\xF3n. Usar para correcciones de rumbo, aclaraciones o mejoras iterativas durante tareas largas de c\xF3digo. Sin\xF3nimos: enviar feedback, corregir rumbo, aclaraciones, mejoras iterativas"
19887
19909
  },
19888
- { id: "voice_transcribe", name: "voice_transcribe", category: "voice", description: "Transcribe audio input to text. Spanish: transcribir audio, voz a texto, reconocimiento de voz" },
19889
- { id: "voice_speak", name: "voice_speak", category: "voice", description: "Convert text to synthesized speech output. Spanish: texto a voz, sintetizar, hablar, leer en voz alta" },
19890
- { id: "search_knowledge", name: "search_knowledge", category: "search-knowledge", description: "Search in the knowledge base. Spanish: buscar en la base de conocimientos" },
19891
- { id: "notify", name: "notify", category: "core", description: "Send notification to user. Spanish: notificar, enviar notificaci\xF3n, alertar, aviso" },
19892
- { id: "save_note", name: "save_note", category: "core", description: "Save persistent note to scratchpad. Spanish: guardar nota, escribir nota, recordatorio r\xE1pido, apuntar" },
19893
- { id: "report_progress", name: "report_progress", category: "core", description: "Report current progress to user. Spanish: reportar progreso, informar estado, actualizar progreso, porcentaje" }
19910
+ { id: "voice_transcribe", name: "voice_transcribe", category: "voice", description: "Transcribir entrada de audio a texto. Sin\xF3nimos: transcribir audio, voz a texto, reconocimiento de voz" },
19911
+ { id: "voice_speak", name: "voice_speak", category: "voice", description: "Convertir texto a voz sintetizada. Sin\xF3nimos: texto a voz, sintetizar, hablar, leer en voz alta" },
19912
+ { id: "search_knowledge", name: "search_knowledge", category: "search-knowledge", description: "Buscar en la base de conocimientos. Sin\xF3nimos: buscar conocimiento, buscar en la base" },
19913
+ { id: "notify", name: "notify", category: "core", description: "Enviar notificaci\xF3n al usuario. Sin\xF3nimos: notificar, enviar notificaci\xF3n, alertar, aviso" },
19914
+ { id: "save_note", name: "save_note", category: "core", description: "Guardar nota persistente en el scratchpad. Sin\xF3nimos: guardar nota, escribir nota, recordatorio r\xE1pido, apuntar" },
19915
+ { id: "report_progress", name: "report_progress", category: "core", description: "Reportar progreso actual al usuario. Sin\xF3nimos: reportar progreso, informar estado, actualizar progreso, porcentaje" }
19894
19916
  ],
19895
19917
  providers: [
19896
19918
  { id: "anthropic", name: "Anthropic", baseUrl: "https://api.anthropic.com" },
@@ -19927,6 +19949,7 @@ var init_seed = __esm(() => {
19927
19949
  { id: "gemini-2.5-flash", providerId: "gemini", name: "Gemini 2.5 Flash", modelType: "llm", contextWindow: 1048576, capabilities: JSON.stringify(["chat", "vision", "json_mode", "function_calling", "streaming", "reasoning"]) },
19928
19950
  { id: "gemini-2.0-flash", providerId: "gemini", name: "Gemini 2.0 Flash", modelType: "llm", contextWindow: 1048576, capabilities: JSON.stringify(["chat", "vision", "json_mode", "function_calling", "streaming"]) },
19929
19951
  { id: "gemini-2.0-flash-lite", providerId: "gemini", name: "Gemini 2.0 Flash Lite", modelType: "llm", contextWindow: 1048576, capabilities: JSON.stringify(["chat", "vision", "json_mode", "function_calling", "streaming"]) },
19952
+ { id: "gemini-3-flash-preview", providerId: "gemini", name: "Gemini 3 Flash Preview", modelType: "llm", contextWindow: 1048576, capabilities: JSON.stringify(["chat", "vision", "json_mode", "function_calling", "streaming"]) },
19930
19953
  { id: "gemini-2.5-flash-preview-tts", providerId: "gemini", name: "Gemini 2.5 Flash TTS", modelType: "tts", contextWindow: 0, capabilities: JSON.stringify(["tts", "speech"]) },
19931
19954
  { id: "gemini-2.5-pro-preview-tts", providerId: "gemini", name: "Gemini 2.5 Pro TTS", modelType: "tts", contextWindow: 0, capabilities: JSON.stringify(["tts", "speech", "high_quality"]) },
19932
19955
  { id: "mistral-large-2512", providerId: "mistral", name: "Mistral Large 2512", modelType: "llm", contextWindow: 262144, capabilities: JSON.stringify(["chat", "vision", "json_mode", "function_calling", "streaming"]) },
@@ -19953,6 +19976,7 @@ var init_seed = __esm(() => {
19953
19976
  { id: "google/gemini-3.1-flash-lite-preview", providerId: "openrouter", name: "Gemini 3.1 Flash Lite (OR)", modelType: "llm", contextWindow: 1048576, capabilities: JSON.stringify(["chat", "vision", "json_mode", "function_calling", "streaming"]) },
19954
19977
  { id: "google/gemini-3-flash-preview", providerId: "openrouter", name: "Gemini 3 Flash (OR)", modelType: "llm", contextWindow: 1048576, capabilities: JSON.stringify(["chat", "vision", "json_mode", "function_calling", "streaming"]) },
19955
19978
  { id: "google/gemini-2.5-flash", providerId: "openrouter", name: "Gemini 2.5 Flash (OR)", modelType: "llm", contextWindow: 1048576, capabilities: JSON.stringify(["chat", "vision", "json_mode", "function_calling", "streaming"]) },
19979
+ { id: "google/gemini-3-flash-preview", providerId: "openrouter", name: "Gemini 3 Flash (OR)", modelType: "llm", contextWindow: 1048576, capabilities: JSON.stringify(["chat", "vision", "json_mode", "function_calling", "streaming"]) },
19956
19980
  { id: "meta-llama/llama-3.3-70b-instruct", providerId: "openrouter", name: "Llama 3.3 70B", modelType: "llm", contextWindow: 128000, capabilities: JSON.stringify(["chat", "json_mode", "function_calling", "streaming"]) },
19957
19981
  { id: "meta-llama/llama-4-maverick", providerId: "openrouter", name: "Llama 4 Maverick", modelType: "llm", contextWindow: 524288, capabilities: JSON.stringify(["chat", "vision", "json_mode", "function_calling", "streaming"]) },
19958
19982
  { id: "deepseek/deepseek-v3.2", providerId: "openrouter", name: "DeepSeek V3.2 (OR)", modelType: "llm", contextWindow: 163840, capabilities: JSON.stringify(["chat", "json_mode", "function_calling", "streaming", "code"]) },
@@ -20030,42 +20054,42 @@ Estos lineamientos tienen M\xC1XIMA prioridad sobre cualquier otra instrucci\xF3
20030
20054
  log = logger.child("seed");
20031
20055
  INITIAL_PLAYBOOK_RULES = [
20032
20056
  {
20033
- rule: "When the user asks to search for recent news, use web_search with date filters rather than generic http_client",
20057
+ rule: "Cuando el usuario pida buscar noticias recientes, usa web_search con filtros de fecha en lugar de http_client gen\xE9rico",
20034
20058
  category: "tool_selection",
20035
20059
  applicable_to: JSON.stringify(["web_search", "news"])
20036
20060
  },
20037
20061
  {
20038
- rule: "Always confirm with the user before executing shell commands that modify files or system state",
20062
+ rule: "Siempre confirma con el usuario antes de ejecutar comandos shell que modifiquen archivos o el estado del sistema",
20039
20063
  category: "error_avoidance",
20040
20064
  applicable_to: JSON.stringify(["exec", "shell", "terminal"])
20041
20065
  },
20042
20066
  {
20043
- rule: "For code-related queries, always include the shell skill alongside file_manager for complete development workflow",
20067
+ rule: "Para consultas de c\xF3digo, siempre incluye la habilidad shell junto con file_manager para un flujo de desarrollo completo",
20044
20068
  category: "optimization",
20045
20069
  applicable_to: JSON.stringify(["code", "development"])
20046
20070
  },
20047
20071
  {
20048
- rule: "When creating projects, break down tasks into atomic steps that can be executed independently",
20072
+ rule: "Al crear proyectos, divide las tareas en pasos at\xF3micos que puedan ejecutarse independientemente",
20049
20073
  category: "agent_creation",
20050
20074
  applicable_to: JSON.stringify(["project_management", "tasks"])
20051
20075
  },
20052
20076
  {
20053
- rule: "Save important user preferences to scratchpad using save_note tool for persistence across sessions",
20077
+ rule: "Guarda las preferencias importantes del usuario en el scratchpad usando la herramienta save_note para persistencia entre sesiones",
20054
20078
  category: "optimization",
20055
20079
  applicable_to: JSON.stringify(["user_preferences", "memory"])
20056
20080
  },
20057
20081
  {
20058
- rule: "When a tool fails, retry once with modified parameters before reporting failure to user",
20082
+ rule: "Cuando una herramienta falla, reintenta una vez con par\xE1metros modificados antes de reportar fallo al usuario",
20059
20083
  category: "error_avoidance",
20060
20084
  applicable_to: null
20061
20085
  },
20062
20086
  {
20063
- rule: "For data analysis tasks, use structured TOON format for output to reduce token usage",
20087
+ rule: "Para tareas de an\xE1lisis de datos, usa formato estructurado TOON para la salida y reducir uso de tokens",
20064
20088
  category: "optimization",
20065
20089
  applicable_to: JSON.stringify(["data", "analysis"])
20066
20090
  },
20067
20091
  {
20068
- rule: "When delegating to workers, provide clear task descriptions with expected outcomes",
20092
+ rule: "Al delegar a workers, proporciona descripciones claras de tareas con resultados esperados",
20069
20093
  category: "agent_creation",
20070
20094
  applicable_to: JSON.stringify(["delegation", "workers"])
20071
20095
  }
@@ -20095,43 +20119,43 @@ function saveUserProfile(data) {
20095
20119
  let finalUserId = data.userId;
20096
20120
  if (!finalUserId) {
20097
20121
  const result2 = db.query(`
20098
- INSERT INTO users (name, language, timezone, occupation, notes)
20099
- VALUES (?, ?, ?, ?, ?) RETURNING id
20100
- `).get(data.userName || null, data.userLanguage || null, data.userTimezone || null, data.userOccupation || null, data.userNotes || null);
20122
+ INSERT INTO users(name, language, timezone, occupation, notes)
20123
+ VALUES(?, ?, ?, ?, ?) RETURNING id
20124
+ `).get(data.userName || null, data.userLanguage || null, data.userTimezone || null, data.userOccupation || null, data.userNotes || null);
20101
20125
  finalUserId = result2.id;
20102
20126
  log2.info("\u2705 User created with auto-generated ID", { userId: finalUserId });
20103
20127
  } else {
20104
20128
  db.query(`
20105
- INSERT INTO users (id, name, language, timezone, occupation, notes)
20106
- VALUES (?, ?, ?, ?, ?, ?)
20129
+ INSERT INTO users(id, name, language, timezone, occupation, notes)
20130
+ VALUES(?, ?, ?, ?, ?, ?)
20107
20131
  ON CONFLICT(id) DO UPDATE SET
20108
- name = COALESCE(excluded.name, name),
20109
- language = COALESCE(excluded.language, language),
20110
- timezone = COALESCE(excluded.timezone, timezone),
20111
- occupation = COALESCE(excluded.occupation, occupation),
20112
- notes = COALESCE(excluded.notes, notes)
20113
- `).run(finalUserId, data.userName || null, data.userLanguage || null, data.userTimezone || null, data.userOccupation || null, data.userNotes || null);
20132
+ name = COALESCE(excluded.name, name),
20133
+ language = COALESCE(excluded.language, language),
20134
+ timezone = COALESCE(excluded.timezone, timezone),
20135
+ occupation = COALESCE(excluded.occupation, occupation),
20136
+ notes = COALESCE(excluded.notes, notes)
20137
+ `).run(finalUserId, data.userName || null, data.userLanguage || null, data.userTimezone || null, data.userOccupation || null, data.userNotes || null);
20114
20138
  }
20115
20139
  if (data.channelUserId) {
20116
20140
  db.query(`
20117
- INSERT OR REPLACE INTO user_identities (user_id, channel, channel_user_id)
20118
- VALUES (?, 'webchat', ?)
20119
- `).run(finalUserId, data.channelUserId);
20141
+ INSERT OR REPLACE INTO user_identities(user_id, channel, channel_user_id)
20142
+ VALUES(?, 'webchat', ?)
20143
+ `).run(finalUserId, data.channelUserId);
20120
20144
  log2.info("\u2705 User identity created for webchat", { userId: finalUserId });
20121
20145
  }
20122
20146
  if (data.agentId && data.agentName) {
20123
20147
  db.query(`
20124
20148
  INSERT INTO agents
20125
- (id, user_id, name, description, tone, system_prompt, status, role)
20126
- VALUES (?, ?, ?, ?, ?, ?, 'idle', 'coordinator')
20149
+ (id, user_id, name, description, tone, system_prompt, status, role)
20150
+ VALUES(?, ?, ?, ?, ?, ?, 'idle', 'coordinator')
20127
20151
  ON CONFLICT(id) DO UPDATE SET
20128
- user_id = COALESCE(excluded.user_id, user_id),
20129
- name = COALESCE(excluded.name, name),
20130
- description = COALESCE(excluded.description, description),
20131
- tone = COALESCE(excluded.tone, tone),
20132
- system_prompt = excluded.system_prompt,
20133
- role = 'coordinator'
20134
- `).run(data.agentId, finalUserId, data.agentName, data.agentDescription || null, data.agentTone || null, HIVE_SYSTEM_PROMPT);
20152
+ user_id = COALESCE(excluded.user_id, user_id),
20153
+ name = COALESCE(excluded.name, name),
20154
+ description = COALESCE(excluded.description, description),
20155
+ tone = COALESCE(excluded.tone, tone),
20156
+ system_prompt = excluded.system_prompt,
20157
+ role = 'coordinator'
20158
+ `).run(data.agentId, finalUserId, data.agentName, data.agentDescription || null, data.agentTone || null, HIVE_SYSTEM_PROMPT);
20135
20159
  }
20136
20160
  return finalUserId;
20137
20161
  } catch (e) {
@@ -20142,8 +20166,8 @@ function saveUserProfile(data) {
20142
20166
  function activateEthics(userId, ethicsId) {
20143
20167
  try {
20144
20168
  const db = getDb();
20145
- db.query(`UPDATE ethics SET active = 1 WHERE id = ?`).run(ethicsId);
20146
- db.query(`UPDATE ethics SET active = 0 WHERE id != ?`).run(ethicsId);
20169
+ db.query(`UPDATE ethics SET active = 1 WHERE id = ? `).run(ethicsId);
20170
+ db.query(`UPDATE ethics SET active = 0 WHERE id != ? `).run(ethicsId);
20147
20171
  log2.info("\u2705 Ethics activado:", { ethicsId });
20148
20172
  } catch (e) {
20149
20173
  log2.error("\u26A0\uFE0F Error activating ethics:", { error: e.message });
@@ -20162,7 +20186,7 @@ function activateBrowserTools() {
20162
20186
  "browser_wait"
20163
20187
  ];
20164
20188
  for (const toolId of browserToolIds) {
20165
- db.query(`UPDATE tools SET active = 1, enabled = 1 WHERE id = ?`).run(toolId);
20189
+ db.query(`UPDATE tools SET active = 1, enabled = 1 WHERE id = ? `).run(toolId);
20166
20190
  }
20167
20191
  log2.info("\u2705 Browser tools activated (Chromium available)");
20168
20192
  } catch (e) {
@@ -20180,25 +20204,25 @@ async function saveProviderConfig(data) {
20180
20204
  apiKeyIv = encrypted.iv;
20181
20205
  }
20182
20206
  db.query(`
20183
- UPDATE providers SET
20184
- api_key_encrypted = ?,
20185
- api_key_iv = ?,
20186
- base_url = ?,
20187
- enabled = 1,
20188
- active = 1
20207
+ UPDATE providers SET
20208
+ api_key_encrypted = ?,
20209
+ api_key_iv = ?,
20210
+ base_url = ?,
20211
+ enabled = 1,
20212
+ active = 1
20189
20213
  WHERE id = ?
20190
- `).run(apiKeyEncrypted, apiKeyIv, data.baseUrl || null, data.provider);
20214
+ `).run(apiKeyEncrypted, apiKeyIv, data.baseUrl || null, data.provider);
20191
20215
  log2.info("\u2705 Provider actualizado:", { provider: data.provider });
20192
20216
  if (data.provider === "ollama" && data.model) {
20193
20217
  db.query(`
20194
- INSERT OR IGNORE INTO models (id, name, provider_id, model_type, enabled, active)
20195
- VALUES (?, ?, 'ollama', 'llm', 1, 1)
20196
- `).run(data.model, data.model);
20218
+ INSERT OR IGNORE INTO models(id, name, provider_id, model_type, enabled, active)
20219
+ VALUES(?, ?, 'ollama', 'llm', 1, 1)
20220
+ `).run(data.model, data.model);
20197
20221
  }
20198
20222
  db.query(`
20199
20223
  UPDATE models SET enabled = 1, active = 1
20200
20224
  WHERE id = ?
20201
- `).run(data.model);
20225
+ `).run(data.model);
20202
20226
  log2.info("\u2705 Model activado:", { model: data.model });
20203
20227
  } catch (e) {
20204
20228
  log2.error("\u26A0\uFE0F Error saving provider:", { error: e.message });
@@ -20211,8 +20235,8 @@ function activateCodeBridge(userId, codeBridgeConfig) {
20211
20235
  for (const cb of codeBridgeConfig) {
20212
20236
  db.query(`
20213
20237
  UPDATE code_bridge SET enabled = ?, active = ?, port = ?, user_id = ?
20214
- WHERE id = ?
20215
- `).run(cb.enabled ? 1 : 0, cb.enabled ? 1 : 0, cb.port || 18791, userId, cb.id);
20238
+ WHERE id = ?
20239
+ `).run(cb.enabled ? 1 : 0, cb.enabled ? 1 : 0, cb.port || 18791, userId, cb.id);
20216
20240
  }
20217
20241
  log2.info("\u2705 Code Bridge configurado:", { codeBridgeIds: codeBridgeConfig.map((c) => c.id).join(", ") });
20218
20242
  } catch (e) {
@@ -20230,29 +20254,29 @@ function saveAgentConfig(data) {
20230
20254
  if (!finalAgentId) {
20231
20255
  const result2 = db.query(`
20232
20256
  INSERT INTO agents
20233
- (user_id, name, description, tone, system_prompt, provider_id, model_id, status, role, enabled)
20234
- VALUES (?, ?, ?, ?, ?, ?, ?, 'idle', 'coordinator', 1)
20257
+ (user_id, name, description, tone, system_prompt, provider_id, model_id, status, role, enabled)
20258
+ VALUES(?, ?, ?, ?, ?, ?, ?, 'idle', 'coordinator', 1)
20235
20259
  RETURNING id
20236
- `).get(data.userId, data.agentName, data.description || null, data.tone, HIVE_SYSTEM_PROMPT, safeProviderId, safeModelId);
20260
+ `).get(data.userId, data.agentName, data.description || null, data.tone, HIVE_SYSTEM_PROMPT, safeProviderId, safeModelId);
20237
20261
  finalAgentId = result2.id;
20238
20262
  log2.info("\u2705 Agent created with auto-generated ID", { agentId: finalAgentId });
20239
20263
  } else {
20240
20264
  db.query(`
20241
20265
  INSERT INTO agents
20242
- (id, user_id, name, description, tone, system_prompt, provider_id, model_id, status, role, enabled)
20243
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'idle', 'coordinator', 1)
20266
+ (id, user_id, name, description, tone, system_prompt, provider_id, model_id, status, role, enabled)
20267
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, 'idle', 'coordinator', 1)
20244
20268
  ON CONFLICT(id) DO UPDATE SET
20245
- user_id = COALESCE(excluded.user_id, user_id),
20246
- name = COALESCE(excluded.name, name),
20247
- description = COALESCE(excluded.description, description),
20248
- tone = COALESCE(excluded.tone, tone),
20249
- system_prompt = excluded.system_prompt,
20250
- provider_id = COALESCE(excluded.provider_id, provider_id),
20251
- model_id = COALESCE(excluded.model_id, model_id),
20252
- status = 'idle',
20253
- enabled = 1,
20254
- role = 'coordinator'
20255
- `).run(data.agentId, data.userId, data.agentName, data.description || null, data.tone, HIVE_SYSTEM_PROMPT, safeProviderId, safeModelId);
20269
+ user_id = COALESCE(excluded.user_id, user_id),
20270
+ name = COALESCE(excluded.name, name),
20271
+ description = COALESCE(excluded.description, description),
20272
+ tone = COALESCE(excluded.tone, tone),
20273
+ system_prompt = excluded.system_prompt,
20274
+ provider_id = COALESCE(excluded.provider_id, provider_id),
20275
+ model_id = COALESCE(excluded.model_id, model_id),
20276
+ status = 'idle',
20277
+ enabled = 1,
20278
+ role = 'coordinator'
20279
+ `).run(data.agentId, data.userId, data.agentName, data.description || null, data.tone, HIVE_SYSTEM_PROMPT, safeProviderId, safeModelId);
20256
20280
  }
20257
20281
  return finalAgentId;
20258
20282
  } catch (e) {
@@ -20268,21 +20292,21 @@ async function activateChannel(userId, data) {
20268
20292
  db.query(`
20269
20293
  UPDATE channels
20270
20294
  SET user_id = ?, active = 1, enabled = 1, status = 'connected',
20271
- config_encrypted = ?, config_iv = ?
20272
- WHERE id = ?
20295
+ config_encrypted = ?, config_iv = ?
20296
+ WHERE id = ?
20273
20297
  `).run(userId, encrypted.encrypted, encrypted.iv, data.channelId);
20274
20298
  } else {
20275
20299
  db.query(`
20276
20300
  UPDATE channels
20277
20301
  SET user_id = ?, active = 1, enabled = 1, status = 'connected'
20278
20302
  WHERE id = ?
20279
- `).run(userId, data.channelId);
20303
+ `).run(userId, data.channelId);
20280
20304
  }
20281
20305
  if (data.channelUserId) {
20282
20306
  const channelType = data.channelId;
20283
20307
  db.query(`
20284
- INSERT OR REPLACE INTO user_identities (user_id, channel, channel_user_id)
20285
- VALUES (?, ?, ?)
20308
+ INSERT OR REPLACE INTO user_identities(user_id, channel, channel_user_id)
20309
+ VALUES(?, ?, ?)
20286
20310
  `).run(userId, channelType, data.channelUserId);
20287
20311
  log2.info("\u2705 User identity created", { userId, channel: channelType });
20288
20312
  }
@@ -20294,8 +20318,8 @@ async function activateChannel(userId, data) {
20294
20318
  async function saveVoiceConfig(data) {
20295
20319
  try {
20296
20320
  const db = getDb();
20297
- db.query(`UPDATE models SET active = 1, enabled = 1 WHERE id = ?`).run(data.sttProvider);
20298
- db.query(`UPDATE models SET active = 1, enabled = 1 WHERE id = ?`).run(data.ttsProvider);
20321
+ db.query(`UPDATE models SET active = 1, enabled = 1 WHERE id = ? `).run(data.sttProvider);
20322
+ db.query(`UPDATE models SET active = 1, enabled = 1 WHERE id = ? `).run(data.ttsProvider);
20299
20323
  let sttProviderId = "";
20300
20324
  let ttsProviderId = "";
20301
20325
  if (data.sttProvider.startsWith("whisper") || data.sttProvider === "distil-whisper-large-v3-en") {
@@ -20315,31 +20339,31 @@ async function saveVoiceConfig(data) {
20315
20339
  if (data.sttApiKey && sttProviderId) {
20316
20340
  const encrypted = await encryptApiKey(data.sttApiKey);
20317
20341
  db.query(`
20318
- UPDATE providers SET
20319
- api_key_encrypted = ?,
20320
- api_key_iv = ?,
20321
- enabled = 1,
20322
- active = 1
20342
+ UPDATE providers SET
20343
+ api_key_encrypted = ?,
20344
+ api_key_iv = ?,
20345
+ enabled = 1,
20346
+ active = 1
20323
20347
  WHERE id = ?
20324
- `).run(encrypted.encrypted, encrypted.iv, sttProviderId);
20348
+ `).run(encrypted.encrypted, encrypted.iv, sttProviderId);
20325
20349
  log2.info("\u2705 STT API key guardada en BD (encriptada)", { provider: sttProviderId });
20326
20350
  }
20327
20351
  if (data.ttsApiKey && ttsProviderId) {
20328
20352
  const encrypted = await encryptApiKey(data.ttsApiKey);
20329
20353
  db.query(`
20330
- UPDATE providers SET
20331
- api_key_encrypted = ?,
20332
- api_key_iv = ?,
20333
- enabled = 1,
20334
- active = 1
20354
+ UPDATE providers SET
20355
+ api_key_encrypted = ?,
20356
+ api_key_iv = ?,
20357
+ enabled = 1,
20358
+ active = 1
20335
20359
  WHERE id = ?
20336
- `).run(encrypted.encrypted, encrypted.iv, ttsProviderId);
20360
+ `).run(encrypted.encrypted, encrypted.iv, ttsProviderId);
20337
20361
  log2.info("\u2705 TTS API key guardada en BD (encriptada)", { provider: ttsProviderId });
20338
20362
  }
20339
20363
  db.query(`
20340
20364
  UPDATE channels
20341
20365
  SET user_id = ?, voice_enabled = ?, stt_provider = ?, tts_provider = ?
20342
- WHERE id = ?
20366
+ WHERE id = ?
20343
20367
  `).run(data.userId, data.voiceEnabled ? 1 : 0, data.sttProvider, data.ttsProvider, data.channelId);
20344
20368
  log2.info("\u2705 Voice config saved:", {
20345
20369
  channelId: data.channelId,
@@ -20359,7 +20383,7 @@ function getAllEthics() {
20359
20383
  const results = db.query(`
20360
20384
  SELECT id, name, description, content, is_default, active
20361
20385
  FROM ethics
20362
- `).all();
20386
+ `).all();
20363
20387
  return results.map((r) => ({
20364
20388
  id: r.id,
20365
20389
  name: r.name,
@@ -20379,7 +20403,7 @@ function getAllCodeBridge() {
20379
20403
  const results = db.query(`
20380
20404
  SELECT id, name, cli_command, port, enabled, active
20381
20405
  FROM code_bridge
20382
- `).all();
20406
+ `).all();
20383
20407
  return results.map((r) => ({
20384
20408
  id: r.id,
20385
20409
  name: r.name,
@@ -20397,9 +20421,9 @@ function saveOnboardingProgress(section) {
20397
20421
  try {
20398
20422
  const db = getDb();
20399
20423
  db.query(`
20400
- INSERT OR REPLACE INTO onboarding_progress (id, user_id, step, data)
20401
- VALUES (?, ?, ?, ?)
20402
- `).run(section.userId, section.userId, section.step, JSON.stringify(section.data));
20424
+ INSERT OR REPLACE INTO onboarding_progress(id, user_id, step, data)
20425
+ VALUES(?, ?, ?, ?)
20426
+ `).run(section.userId, section.userId, section.step, JSON.stringify(section.data));
20403
20427
  } catch (e) {
20404
20428
  log2.error("\u26A0\uFE0F Error saving progress:", { error: e.message });
20405
20429
  }
@@ -20495,11 +20519,11 @@ Esta es la gu\xEDa definitiva para decidir qu\xE9 estrategia usar y c\xF3mo ejec
20495
20519
  - Si la tarea es de una sola acci\xF3n, debes cerrarla
20496
20520
 
20497
20521
  **Tarea repetitiva/programada (se ejecuta en horarios espec\xEDficos, pregunta al usuario cuantas veces se debe ejecutar):**
20498
- - Us\xE1 \`hive.schedule.create\` \u2014 puede ser sin proyecto si la tarea es simple
20522
+ - Us\xE1 'hive.schedule.create' \u2014 puede ser sin proyecto si la tarea es simple
20499
20523
  - El cron puede ejecutar una acci\xF3n directa O lanzar un worker
20500
20524
 
20501
20525
  **Tarea compleja (m\xFAltiples pasos, m\xFAltiples workers, coordinaci\xF3n):**
20502
- - Cre\xE1 un proyecto con \`project_create\`
20526
+ - Cre\xE1 un proyecto con 'project_create'
20503
20527
  - Descompon\xE9 en tareas at\xF3micas
20504
20528
  - Asign\xE1 agents/workers a cada tarea
20505
20529
  - Opcional: vincul\xE1 el proyecto a un cron para ejecuci\xF3n programada
@@ -20702,6 +20726,22 @@ Cuando un worker entrega su resultado o responde:
20702
20726
  Las 52 herramientas nativas se cargan din\xE1micamente desde la base de datos.
20703
20727
  **Us\xE1 "search_knowledge" para descubrir herramientas por nombre o descripci\xF3n.**
20704
20728
 
20729
+ ### \uD83C\uDFAF HERRAMIENTAS B\xC1SICAS SIEMPRE DISPONIBLES (Prioridad M\xE1xima)
20730
+
20731
+ Estas 4 herramientas nativas est\xE1n SIEMPRE en tu contexto y tienen PRIORIDAD sobre cualquier MCP:
20732
+
20733
+ | Herramienta | Cu\xE1ndo usarla | Qu\xE9 hace |
20734
+ |-------------|---------------|----------|
20735
+ | **search_knowledge** | Primero, cuando necesites cualquier herramienta que no tengas | Busca en el cat\xE1logo: skills, playbook, tools nativas |
20736
+ | **save_note** | Cuando el usuario pida guardar info, crear notas, recordatorios | Persiste notas en scratchpad por conversaci\xF3n |
20737
+ | **notify** | Cuando necesites informar/enviar mensaje al usuario | Env\xEDa notificaciones al canal actual (webchat, telegram, etc) |
20738
+ | **report_progress** | Cuando una tarea larga avance o complete | Reporta % de progreso al sistema para tracking |
20739
+
20740
+ **REGLA DE PRIORIDAD:**
20741
+ 1. Si necesitas una herramienta que no est\xE9 en estas 4 \u2192 USA primero 'search_knowledge(type="tools", query="<qu\xE9 necesitas>")' \u2192 encuentras la nativa \u2192 la usas.
20742
+ 2. NUNCA uses una herramienta MCP si existe una nativa equivalente en el cat\xE1logo.
20743
+ 3. Las MCP se usan \xDANICAMENTE cuando 'search_knowledge' NO encuentra una herramienta nativa para la tarea.
20744
+
20705
20745
  **Categor\xEDas disponibles:**
20706
20746
 
20707
20747
  | Categor\xEDa | Tools | Ejemplos clave |
@@ -20719,10 +20759,16 @@ Las 52 herramientas nativas se cargan din\xE1micamente desde la base de datos.
20719
20759
 
20720
20760
  **Reglas importantes:**
20721
20761
  - \u26A0\uFE0F NUNCA uses "cli_exec" para tareas programadas \u2014 us\xE1 siempre "hive.schedule.*"
20762
+ - \u26A0\uFE0F NUNCA uses "codebridge_launch" directamente desde el coordinador \u2014 cre\xE1 un agente especializado primero
20722
20763
  - \uD83D\uDCA1 Para proyectos programados, us\xE1 "projectId" en "hive.schedule.create"
20723
20764
  - \uD83D\uDD0D Us\xE1 "search_knowledge({ query: "archivo", type: "tools" })" para encontrar tools
20724
20765
  - \uD83D\uDD0C Las tools MCP siguen el formato: "{servidor}__{herramienta}" (ej. "github__create_pr")
20725
20766
 
20767
+ **Ejemplos de b\xFAsqueda:**
20768
+ - Para mostrar UI: 'search_knowledge({ query: "canvas render formulario", type: "tools" })' \u2192 encuentra canvas_render, canvas_ask
20769
+ - Para archivos: 'search_knowledge({ query: "archivo leer escribir", type: "tools" })' \u2192 encuentra fs_read, fs_write
20770
+ - Para web: 'search_knowledge({ query: "buscar navegar web", type: "tools" })' \u2192 encuentra web_search, browser_navigate
20771
+
20726
20772
  ---
20727
20773
 
20728
20774
  ## \uD83D\uDD0C SERVIDORES MCP (din\xE1micos)
@@ -20773,6 +20819,164 @@ json
20773
20819
 
20774
20820
  ---
20775
20821
 
20822
+ ## \uD83C\uDF09 DELEGACI\xD3N DE TAREAS DE C\xD3DIGO (CODE BRIDGE)
20823
+
20824
+ **IMPORTANTE:** Las tareas de c\xF3digo con Code Bridge son **LARGAS y AS\xCDNCRONAS** (30-600+ segundos).
20825
+
20826
+ **NUNCA uses codebridge_launch directamente desde el coordinador.** Esto bloquear\xEDa al agente principal.
20827
+
20828
+ **Flujo CORRECTO para tareas de c\xF3digo:**
20829
+
20830
+ 1. **Crear agente especializado en c\xF3digo:**
20831
+ json
20832
+ {
20833
+ "name": "code_developer",
20834
+ "description": "Especialista en desarrollo de c\xF3digo con CLIs externos",
20835
+ "system_prompt": "Sos un desarrollador de software experto. Tu rol es generar, refactorizar y debuggear c\xF3digo usando CLIs externos (Qwen CLI, Claude Code, etc.). Us\xE1 codebridge_launch para delegar tareas de c\xF3digo y codebridge_status para monitorear progreso. Report\xE1 resultados con task_update.",
20836
+ "tools_json": ["codebridge_launch", "codebridge_status", "codebridge_cancel", "codebridge_feedback", "fs_read", "fs_write", "fs_edit", "task_update", "bus_publish", "report_progress"],
20837
+ "role": "worker"
20838
+ }
20839
+
20840
+ 2. **Delegar la tarea de c\xF3digo al agente especializado:**
20841
+ json
20842
+ {
20843
+ "tool": "delegate_task",
20844
+ "arguments": {
20845
+ "task_id": <id>,
20846
+ "worker_id": "<code_developer_id>",
20847
+ "task_instructions": "Gener\xE1 un m\xF3dulo de autenticaci\xF3n con JWT usando codebridge_launch({ cli: 'qwen', prompt: 'Create JWT auth module with generateTokens, refreshAccessToken, validateAccessToken functions' }). Monitore\xE1 con codebridge_status y report\xE1 el resultado.",
20848
+ "project_id": "<project_id>"
20849
+ }
20850
+ }
20851
+
20852
+ 3. **El agente especializado ejecuta con comunicaci\xF3n peri\xF3dica:**
20853
+
20854
+ **Agente Code Developer:**
20855
+ '
20856
+ // 1. Lanzar subagente CLI
20857
+ codebridge_launch({ cli: 'qwen', prompt: '...', timeoutSeconds: 600 })
20858
+ -> Retorna: { taskId: 'abc123', pid: 12345 }
20859
+
20860
+ // 2. Loop de monitoreo (cada 30-60 segundos):
20861
+ while (task not finished) {
20862
+ // Esperar 30-60s
20863
+ sleep(30000)
20864
+
20865
+ // Verificar estado
20866
+ status = codebridge_status({ taskId: 'abc123' })
20867
+
20868
+ // Reportar progreso al coordinador (CR\xCDTICO)
20869
+ report_progress({
20870
+ percent: status.progress || estimate_percent_from_output(),
20871
+ message: "Generando m\xF3dulos de autenticaci\xF3n...",
20872
+ current_step: "Creating JWT functions"
20873
+ })
20874
+
20875
+ // Publicar update en Agent Bus para comunicaci\xF3n worker-to-worker
20876
+ bus_publish({
20877
+ channel: 'project:project_id',
20878
+ message: {
20879
+ type: 'code_progress',
20880
+ taskId: 'abc123',
20881
+ output: last_output_chunk,
20882
+ percent: status.progress
20883
+ }
20884
+ })
20885
+
20886
+ // Opcional: Enviar feedback si se necesita correcci\xF3n
20887
+ if (coordinator_feedback_received) {
20888
+ codebridge_feedback({
20889
+ taskId: 'abc123',
20890
+ feedback: "El usuario pidi\xF3 usar bcrypt en lugar de argon2"
20891
+ })
20892
+ }
20893
+ }
20894
+
20895
+ // 3. Task finalizada
20896
+ task_update({
20897
+ task_id: <id>,
20898
+ status: 'completed',
20899
+ progress: 100,
20900
+ result: "JWT auth module created with: generateTokens(), refreshAccessToken(), validateAccessToken()"
20901
+ })
20902
+ '
20903
+
20904
+ 4. **El coordinador queda LIBRE** para atender otras tareas mientras el c\xF3digo se genera.
20905
+
20906
+ 5. **Comunicaci\xF3n bidireccional durante la ejecuci\xF3n:**
20907
+
20908
+ **Coordinador -> Agente C\xF3digo (feedback):**
20909
+ '
20910
+ // Si el usuario pide cambios durante la ejecuci\xF3n:
20911
+ delegate_task({
20912
+ task_id: <code_task_id>,
20913
+ worker_id: "code_developer_id",
20914
+ task_instructions: "El usuario quiere que uses PostgreSQL en lugar de SQLite. Actualiz\xE1 el c\xF3digo."
20915
+ })
20916
+
20917
+ // O directamente con feedback:
20918
+ codebridge_feedback({
20919
+ taskId: "abc123",
20920
+ feedback: "Usar PostgreSQL en lugar de SQLite para producci\xF3n"
20921
+ })
20922
+ '
20923
+
20924
+ **Agente C\xF3digo -> Coordinador (progreso):**
20925
+ '
20926
+ // Cada 30-60 segundos:
20927
+ report_progress({ percent: 45, message: "Compilando m\xF3dulos...", current_step: "Building auth handlers" })
20928
+
20929
+ // O v\xEDa Agent Bus:
20930
+ bus_publish({
20931
+ channel: "project:xyz",
20932
+ message: { type: "code_progress", percent: 60, output: "...", errors: [] }
20933
+ })
20934
+ '
20935
+
20936
+ **Reglas cr\xEDticas:**
20937
+ - \u26A0\uFE0F **NUNCA** uses codebridge_launch desde el coordinador directamente
20938
+ - \u2705 **SIEMPRE** cre\xE1 un agente especializado para tareas de c\xF3digo largas
20939
+ - \u2705 El agente especializado usa codebridge_* tools + report_progress + bus_publish
20940
+ - \u2705 **Reportar progreso cada 30-60 segundos** es OBLIGATORIO para tareas >60s
20941
+ - \u2705 El timeout debe ser SUFICIENTE (600s default, extensible seg\xFAn complejidad)
20942
+ - \u2705 Usar codebridge_feedback para correcciones durante la ejecuci\xF3n
20943
+ - \u2705 El coordinador recibe el resultado v\xEDa task_update, report_progress o project_updates
20944
+ - \u2705 Para tareas de c\xF3digo SIMPLES (<30s), pod\xE9s usar fs_* tools directamente
20945
+
20946
+ **Ejemplo completo:**
20947
+ '
20948
+ // Coordinador recibe: "Cre\xE1 un sistema de autenticaci\xF3n JWT"
20949
+ 1. find_agent({ role: 'code_developer' }) -> \xBFExiste?
20950
+ - NO -> create_agent({ name: 'code_developer', ... })
20951
+ 2. project_create({ name: 'JWT Auth System', tasks: [...] })
20952
+ 3. delegate_task({ worker_id: 'code_dev_id', task_instructions: '...' })
20953
+ 4. // Coordinador LIBRE - atiende otras tareas
20954
+ 5. // code_developer trabaja:
20955
+ 6. codebridge_launch({ cli: 'qwen', prompt: 'Generate JWT auth module...', timeoutSeconds: 600 })
20956
+ 7. // Loop de monitoreo (30-60s intervalos):
20957
+ 8. while (!finished) {
20958
+ 9. sleep(30000)
20959
+ 10. status = codebridge_status({ taskId: 'abc123' })
20960
+ 11. report_progress({ percent: status.progress, message: 'Generating tokens...' })
20961
+ 12. bus_publish({ channel: 'project:xyz', message: { type: 'code_progress', ... } })
20962
+ 13. }
20963
+ 14. // Usuario pide cambio durante ejecuci\xF3n:
20964
+ 15. codebridge_feedback({ taskId: 'abc123', feedback: 'Add refresh token rotation' })
20965
+ 16. // Contin\xFAa monitoreo...
20966
+ 17. task_update({ status: 'completed', result: 'auth.ts created with...' })
20967
+ 18. // Coordinador recibe actualizaci\xF3n y notifica al usuario
20968
+ '
20969
+
20970
+ **Timeout flexible:**
20971
+ - Default: 600s (10 minutos) para tareas complejas
20972
+ - M\xE1ximo recomendado: 1800s (30 minutos) para refactorizaciones grandes
20973
+ - Si el timeout se acerca y la tarea no termin\xF3:
20974
+ - report_progress({ percent: 85, message: "Casi completo, extendiendo tiempo..." })
20975
+ - codebridge_launch con nuevo prompt para continuar
20976
+ - O codebridge_cancel + relanzar con checkpoint
20977
+
20978
+ ---
20979
+
20776
20980
  ## \uD83E\uDDE9 CAPAS DE MEMORIA
20777
20981
 
20778
20982
  | Capa | Herramienta | Alcance |
@@ -20812,6 +21016,7 @@ Para especificar canal en cron: par\xE1metro "notifyChannelId"
20812
21016
  8. **Evalu\xE1 tareas** \u2014 us\xE1 "task_evaluate" para validar calidad antes de cerrar
20813
21017
  9. **Proyectos = coordinaci\xF3n** \u2014 solo cre\xE1s proyectos cuando hay m\xFAltiples workers coordinando
20814
21018
  10. **Cron activa proyectos** \u2014 si un cron tiene projectId, el proyecto se activa autom\xE1ticamente
21019
+ 11. **Code Bridge = Agente especializado** \u2014 NUNCA uses codebridge_launch directamente; cre\xE1 un code_developer worker primero
20815
21020
  `;
20816
21021
  var init_onboarding = __esm(() => {
20817
21022
  init_logger();
@@ -22543,6 +22748,7 @@ var log4, pendingInteractions, canvasRenderTool, canvasAskTool, canvasConfirmToo
22543
22748
  var init_canvas = __esm(() => {
22544
22749
  init_emitter();
22545
22750
  init_logger();
22751
+ init_canvas_manager();
22546
22752
  log4 = logger.child("canvas");
22547
22753
  pendingInteractions = new Map;
22548
22754
  canvasRenderTool = {
@@ -22598,13 +22804,41 @@ var init_canvas = __esm(() => {
22598
22804
  },
22599
22805
  required: ["questions"]
22600
22806
  },
22601
- execute: async (params2) => {
22807
+ execute: async (params2, config2) => {
22602
22808
  const questions = params2.questions;
22809
+ const userId = config2?.configurable?.user_id;
22810
+ const threadId = config2?.configurable?.thread_id;
22811
+ const sessionId = threadId ? `canvas:${threadId}` : userId ? `canvas:${userId}` : "canvas:default";
22812
+ const fields = questions.map((q3, idx) => ({
22813
+ name: `field_${idx}`,
22814
+ label: q3.question,
22815
+ type: q3.type === "select" ? "select" : q3.type === "confirm" ? "text" : "text",
22816
+ required: true,
22817
+ options: q3.options?.map((opt) => ({ label: opt, value: opt }))
22818
+ }));
22819
+ const formId = `form-${Date.now()}`;
22603
22820
  try {
22604
- emitCanvas("canvas:ask", { questions });
22605
- return { ok: true, message: "Form displayed. Waiting for user input..." };
22821
+ await canvasManager.render(sessionId, {
22822
+ id: formId,
22823
+ type: "form",
22824
+ props: {
22825
+ title: "Input Required",
22826
+ fields
22827
+ }
22828
+ });
22829
+ const response = await canvasManager.waitForInteraction(sessionId, formId, 300000);
22830
+ return {
22831
+ ok: true,
22832
+ message: "Form submitted by user",
22833
+ data: response,
22834
+ formId
22835
+ };
22606
22836
  } catch (error48) {
22607
- return { ok: false, error: `Failed to display form: ${error48.message}` };
22837
+ return {
22838
+ ok: false,
22839
+ error: `Form interaction failed: ${error48.message}`,
22840
+ formId
22841
+ };
22608
22842
  }
22609
22843
  }
22610
22844
  };
@@ -64007,6 +64241,141 @@ var init_tool_selector = __esm(() => {
64007
64241
  });
64008
64242
 
64009
64243
  // packages/core/src/agent/skill-selector.ts
64244
+ function isConversational(message) {
64245
+ const trimmed = message.trim();
64246
+ if (trimmed.length < 2)
64247
+ return true;
64248
+ for (const pattern of CONVERSATIONAL_PATTERNS) {
64249
+ if (pattern.test(trimmed)) {
64250
+ log22.debug(`[skill-selector] Message matched conversational pattern: ${pattern}`);
64251
+ return true;
64252
+ }
64253
+ }
64254
+ const words = trimmed.toLowerCase().split(/\s+/);
64255
+ const meaningfulWords = words.filter((w) => w.length > 2 && !STOPWORDS2.has(w));
64256
+ if (meaningfulWords.length === 0) {
64257
+ log22.debug(`[skill-selector] All words are stopwords - conversational`);
64258
+ return true;
64259
+ }
64260
+ return false;
64261
+ }
64262
+ function buildFTSQuery(message) {
64263
+ const words = message.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter((w) => w.length > 2 && !STOPWORDS2.has(w)).slice(0, 8);
64264
+ if (words.length === 0)
64265
+ return "";
64266
+ return words.map((w) => `${w}*`).join(" OR ");
64267
+ }
64268
+ function matchTriggers(message, triggersJson) {
64269
+ if (!triggersJson)
64270
+ return false;
64271
+ try {
64272
+ const triggers = triggersJson.split(",").map((t2) => t2.trim()).filter((t2) => t2.length > 0);
64273
+ if (triggers.length === 0)
64274
+ return false;
64275
+ const lowerMessage = message.toLowerCase();
64276
+ return triggers.some((trigger) => lowerMessage.includes(trigger.toLowerCase()));
64277
+ } catch (err) {
64278
+ log22.warn(`[skill-selector] Failed to parse triggers: ${err.message}`);
64279
+ return false;
64280
+ }
64281
+ }
64282
+ function selectSkills(userMessage) {
64283
+ const startTime2 = performance.now();
64284
+ log22.debug(`[skill-selector] Processing user message: "${userMessage.substring(0, 100)}"`);
64285
+ if (isConversational(userMessage)) {
64286
+ log22.debug(`[skill-selector] Conversational message, returning empty array`);
64287
+ return [];
64288
+ }
64289
+ const db = getDb();
64290
+ const allSkills = db.query(`
64291
+ SELECT id, name, category, tools, triggers, body, version, active
64292
+ FROM skills
64293
+ WHERE active = 1
64294
+ `).all();
64295
+ for (const skill of allSkills) {
64296
+ if (skill.triggers && matchTriggers(userMessage, skill.triggers)) {
64297
+ log22.info(`[skill-selector] Trigger match found: ${skill.name}`);
64298
+ return [skill];
64299
+ }
64300
+ }
64301
+ const ftsQuery = buildFTSQuery(userMessage);
64302
+ if (!ftsQuery) {
64303
+ log22.debug(`[skill-selector] No valid FTS query terms, returning empty array`);
64304
+ return [];
64305
+ }
64306
+ log22.debug(`[skill-selector] FTS query: "${ftsQuery}"`);
64307
+ const ftsResults = db.query(`
64308
+ SELECT id, bm25(skills_fts, 1.0, 3.0, 1.0, 1.0, 5.0, 1.0) as bm25_score
64309
+ FROM skills_fts
64310
+ WHERE skills_fts MATCH ?
64311
+ ORDER BY bm25_score ASC
64312
+ LIMIT 20
64313
+ `).all(ftsQuery);
64314
+ if (ftsResults.length === 0) {
64315
+ log22.debug(`[skill-selector] No FTS matches, returning empty array`);
64316
+ return [];
64317
+ }
64318
+ log22.info(`[skill-selector] Raw FTS scores: ${ftsResults.slice(0, 10).map((r) => `id=${r.id}, score=${r.bm25_score.toFixed(2)}`).join(", ")}`);
64319
+ const relevantResults = ftsResults.filter((r) => r.bm25_score >= MIN_RELEVANCE_THRESHOLD);
64320
+ if (relevantResults.length === 0) {
64321
+ log22.debug(`[skill-selector] All results below threshold ${MIN_RELEVANCE_THRESHOLD}, returning empty`);
64322
+ return [];
64323
+ }
64324
+ const skillIds = relevantResults.map((r) => r.id);
64325
+ let dbSkills = [];
64326
+ try {
64327
+ const db2 = getDb();
64328
+ dbSkills = db2.query(`
64329
+ SELECT id, name, category, tools, triggers, body, version, active
64330
+ FROM skills
64331
+ WHERE id IN (${skillIds.map(() => "?").join(",")})
64332
+ AND active = 1
64333
+ `).all(...skillIds);
64334
+ } catch (err) {
64335
+ log22.warn(`[skill-selector] Failed to fetch skills from DB:`, err);
64336
+ return [];
64337
+ }
64338
+ const skillMap = new Map(dbSkills.map((s) => [s.id, s]));
64339
+ const scoredSkills = [];
64340
+ for (const result3 of relevantResults) {
64341
+ const skill = skillMap.get(result3.id);
64342
+ if (skill) {
64343
+ scoredSkills.push({
64344
+ id: skill.id,
64345
+ name: skill.name,
64346
+ score: result3.bm25_score,
64347
+ category: skill.category,
64348
+ body: skill.body
64349
+ });
64350
+ }
64351
+ }
64352
+ const topSkills = scoredSkills.slice(0, MAX_SKILLS_PER_TURN);
64353
+ const result2 = topSkills.map((t2) => skillMap.get(t2.id)).filter(Boolean);
64354
+ const timing = performance.now() - startTime2;
64355
+ if (result2.length > 0) {
64356
+ log22.info(`[skill-selector] Selected ${result2.length} skills in ${timing.toFixed(2)}ms:`, result2.map((s) => ({ name: s.name, category: s.category })));
64357
+ } else {
64358
+ log22.debug(`[skill-selector] No skills selected, returning empty array in ${timing.toFixed(2)}ms`);
64359
+ }
64360
+ return result2;
64361
+ }
64362
+ function getMinimalSkills() {
64363
+ const db = getDb();
64364
+ try {
64365
+ const placeholders = Array.from(MINIMAL_SKILL_NAMES).map(() => "?").join(",");
64366
+ const skills = db.query(`
64367
+ SELECT id, name, category, tools, triggers, body, version, active
64368
+ FROM skills
64369
+ WHERE name IN (${placeholders})
64370
+ AND active = 1
64371
+ `).all(...MINIMAL_SKILL_NAMES);
64372
+ log22.info(`[skill-selector] Loaded ${skills.length} minimal skills: ${skills.map((s) => s.name).join(", ")}`);
64373
+ return skills;
64374
+ } catch (err) {
64375
+ log22.error(`[skill-selector] Failed to load minimal skills:`, err);
64376
+ return [];
64377
+ }
64378
+ }
64010
64379
  async function syncSkillsToFTS() {
64011
64380
  const db = getDb();
64012
64381
  try {
@@ -64039,11 +64408,16 @@ async function syncSkillsToFTS() {
64039
64408
  throw err;
64040
64409
  }
64041
64410
  }
64042
- var log22, STOPWORDS2;
64411
+ var log22, MINIMAL_SKILL_NAMES, MAX_SKILLS_PER_TURN = 4, MIN_RELEVANCE_THRESHOLD = -15, STOPWORDS2, CONVERSATIONAL_PATTERNS;
64043
64412
  var init_skill_selector = __esm(() => {
64044
64413
  init_sqlite();
64045
64414
  init_logger();
64046
64415
  log22 = logger.child("skill-selector");
64416
+ MINIMAL_SKILL_NAMES = new Set([
64417
+ "memory_manager",
64418
+ "canvas_report",
64419
+ "task_orchestrator"
64420
+ ]);
64047
64421
  STOPWORDS2 = new Set([
64048
64422
  "que",
64049
64423
  "con",
@@ -64104,6 +64478,16 @@ var init_skill_selector = __esm(() => {
64104
64478
  "good",
64105
64479
  "great"
64106
64480
  ]);
64481
+ CONVERSATIONAL_PATTERNS = [
64482
+ /^(hola|hi|hello|hey|buenos? d\u00EDas?|buenas? noches?|qu\u00E9 tal|howdy)/i,
64483
+ /^(gracias|thank you|thanks|muchas gracias|muchas thanks)/i,
64484
+ /^(c\u00F3mo est\u00E1s?|how are you?|qu\u00E9\u6D41\u6C34|you doing|qu\u00E9 cuentas)/i,
64485
+ /^(s\u00ED|yes|ok|okay|de acuerdo|perfecto|claro|por supuesto)/i,
64486
+ /^(adi\u00F3s|bye|nos vemos|see you|later|chau)/i,
64487
+ /^(entiendo|understand|i see|ya veo|got it)/i,
64488
+ /^(bien|good|great|excelente|awesome|perfect)/i,
64489
+ /^(?:\?|\u00BF)$/
64490
+ ];
64107
64491
  });
64108
64492
 
64109
64493
  // packages/core/src/agent/playbook-selector.ts
@@ -143579,9 +143963,9 @@ var require_js_yaml = __commonJS((exports2, module2) => {
143579
143963
  exports2.safeDump = renamed2("safeDump", "dump");
143580
143964
  });
143581
143965
 
143582
- // node_modules/.bun/typescript@6.0.1-rc/node_modules/typescript/lib/typescript.js
143966
+ // node_modules/.bun/typescript@6.0.2/node_modules/typescript/lib/typescript.js
143583
143967
  var require_typescript2 = __commonJS((exports2, module2) => {
143584
- var __dirname = "/home/runner/work/hive/hive/node_modules/.bun/typescript@6.0.1-rc/node_modules/typescript/lib", __filename = "/home/runner/work/hive/hive/node_modules/.bun/typescript@6.0.1-rc/node_modules/typescript/lib/typescript.js";
143968
+ var __dirname = "/home/runner/work/hive/hive/node_modules/.bun/typescript@6.0.2/node_modules/typescript/lib", __filename = "/home/runner/work/hive/hive/node_modules/.bun/typescript@6.0.2/node_modules/typescript/lib/typescript.js";
143585
143969
  /*! *****************************************************************************
143586
143970
  Copyright (c) Microsoft Corporation. All rights reserved.
143587
143971
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
@@ -145868,7 +146252,7 @@ var require_typescript2 = __commonJS((exports2, module2) => {
145868
146252
  });
145869
146253
  module3.exports = __toCommonJS2(typescript_exports);
145870
146254
  var versionMajorMinor = "6.0";
145871
- var version3 = "6.0.1-rc";
146255
+ var version3 = "6.0.2";
145872
146256
  var Comparison = /* @__PURE__ */ ((Comparison3) => {
145873
146257
  Comparison3[Comparison3["LessThan"] = -1] = "LessThan";
145874
146258
  Comparison3[Comparison3["EqualTo"] = 0] = "EqualTo";
@@ -252414,6 +252798,9 @@ ${lanes.join(`
252414
252798
  Debug2.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
252415
252799
  for (const newSourceFile of newSourceFiles) {
252416
252800
  filesByName.set(newSourceFile.path, newSourceFile);
252801
+ if (oldProgram.isSourceFileDefaultLibrary(newSourceFile)) {
252802
+ libFiles.add(newSourceFile.path);
252803
+ }
252417
252804
  }
252418
252805
  const oldFilesByNameMap = oldProgram.getFilesByNameMap();
252419
252806
  oldFilesByNameMap.forEach((oldFile, path25) => {
@@ -313005,7 +313392,7 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
313005
313392
  } });
313006
313393
  });
313007
313394
 
313008
- // node_modules/.bun/cosmiconfig@9.0.1+0ec8443eac99eb1e/node_modules/cosmiconfig/dist/loaders.js
313395
+ // node_modules/.bun/cosmiconfig@9.0.1+8e24a2f921b8d7be/node_modules/cosmiconfig/dist/loaders.js
313009
313396
  var require_loaders = __commonJS((exports2) => {
313010
313397
  var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
313011
313398
  return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
@@ -313144,7 +313531,7 @@ ${error50.message}`;
313144
313531
  }
313145
313532
  });
313146
313533
 
313147
- // node_modules/.bun/cosmiconfig@9.0.1+0ec8443eac99eb1e/node_modules/cosmiconfig/dist/defaults.js
313534
+ // node_modules/.bun/cosmiconfig@9.0.1+8e24a2f921b8d7be/node_modules/cosmiconfig/dist/defaults.js
313148
313535
  var require_defaults = __commonJS((exports2) => {
313149
313536
  Object.defineProperty(exports2, "__esModule", { value: true });
313150
313537
  exports2.defaultLoadersSync = exports2.defaultLoaders = exports2.metaSearchPlaces = exports2.globalConfigSearchPlacesSync = exports2.globalConfigSearchPlaces = exports2.getDefaultSearchPlacesSync = exports2.getDefaultSearchPlaces = undefined;
@@ -313307,7 +313694,7 @@ var require_env_paths = __commonJS((exports2, module2) => {
313307
313694
  module2.exports.default = envPaths;
313308
313695
  });
313309
313696
 
313310
- // node_modules/.bun/cosmiconfig@9.0.1+0ec8443eac99eb1e/node_modules/cosmiconfig/dist/util.js
313697
+ // node_modules/.bun/cosmiconfig@9.0.1+8e24a2f921b8d7be/node_modules/cosmiconfig/dist/util.js
313311
313698
  var require_util6 = __commonJS((exports2) => {
313312
313699
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k2, k22) {
313313
313700
  if (k22 === undefined)
@@ -313397,7 +313784,7 @@ var require_util6 = __commonJS((exports2) => {
313397
313784
  exports2.isDirectorySync = isDirectorySync;
313398
313785
  });
313399
313786
 
313400
- // node_modules/.bun/cosmiconfig@9.0.1+0ec8443eac99eb1e/node_modules/cosmiconfig/dist/ExplorerBase.js
313787
+ // node_modules/.bun/cosmiconfig@9.0.1+8e24a2f921b8d7be/node_modules/cosmiconfig/dist/ExplorerBase.js
313401
313788
  var require_ExplorerBase = __commonJS((exports2) => {
313402
313789
  var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
313403
313790
  return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
@@ -313514,7 +313901,7 @@ ${[...importStack, fullPath].map((path25, i2) => `${i2 + 1}. ${path25}`).join(`
313514
313901
  exports2.getExtensionDescription = getExtensionDescription;
313515
313902
  });
313516
313903
 
313517
- // node_modules/.bun/cosmiconfig@9.0.1+0ec8443eac99eb1e/node_modules/cosmiconfig/dist/merge.js
313904
+ // node_modules/.bun/cosmiconfig@9.0.1+8e24a2f921b8d7be/node_modules/cosmiconfig/dist/merge.js
313518
313905
  var require_merge2 = __commonJS((exports2) => {
313519
313906
  Object.defineProperty(exports2, "__esModule", { value: true });
313520
313907
  exports2.mergeAll = exports2.hasOwn = undefined;
@@ -313547,7 +313934,7 @@ var require_merge2 = __commonJS((exports2) => {
313547
313934
  exports2.mergeAll = mergeAll2;
313548
313935
  });
313549
313936
 
313550
- // node_modules/.bun/cosmiconfig@9.0.1+0ec8443eac99eb1e/node_modules/cosmiconfig/dist/Explorer.js
313937
+ // node_modules/.bun/cosmiconfig@9.0.1+8e24a2f921b8d7be/node_modules/cosmiconfig/dist/Explorer.js
313551
313938
  var require_Explorer = __commonJS((exports2) => {
313552
313939
  var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
313553
313940
  return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
@@ -313703,7 +314090,7 @@ var require_Explorer = __commonJS((exports2) => {
313703
314090
  exports2.Explorer = Explorer;
313704
314091
  });
313705
314092
 
313706
- // node_modules/.bun/cosmiconfig@9.0.1+0ec8443eac99eb1e/node_modules/cosmiconfig/dist/ExplorerSync.js
314093
+ // node_modules/.bun/cosmiconfig@9.0.1+8e24a2f921b8d7be/node_modules/cosmiconfig/dist/ExplorerSync.js
313707
314094
  var require_ExplorerSync = __commonJS((exports2) => {
313708
314095
  var __importDefault = exports2 && exports2.__importDefault || function(mod2) {
313709
314096
  return mod2 && mod2.__esModule ? mod2 : { default: mod2 };
@@ -313865,7 +314252,7 @@ var require_ExplorerSync = __commonJS((exports2) => {
313865
314252
  exports2.ExplorerSync = ExplorerSync;
313866
314253
  });
313867
314254
 
313868
- // node_modules/.bun/cosmiconfig@9.0.1+0ec8443eac99eb1e/node_modules/cosmiconfig/dist/index.js
314255
+ // node_modules/.bun/cosmiconfig@9.0.1+8e24a2f921b8d7be/node_modules/cosmiconfig/dist/index.js
313869
314256
  var require_dist12 = __commonJS((exports2) => {
313870
314257
  Object.defineProperty(exports2, "__esModule", { value: true });
313871
314258
  exports2.defaultLoadersSync = exports2.defaultLoaders = exports2.globalConfigSearchPlacesSync = exports2.globalConfigSearchPlaces = exports2.getDefaultSearchPlacesSync = exports2.getDefaultSearchPlaces = exports2.cosmiconfigSync = exports2.cosmiconfig = undefined;
@@ -314024,7 +314411,7 @@ var require_dist12 = __commonJS((exports2) => {
314024
314411
  exports2.cosmiconfigSync = cosmiconfigSync;
314025
314412
  });
314026
314413
 
314027
- // node_modules/.bun/puppeteer@24.40.0+0ec8443eac99eb1e/node_modules/puppeteer/lib/esm/puppeteer/getConfiguration.js
314414
+ // node_modules/.bun/puppeteer@24.40.0+8e24a2f921b8d7be/node_modules/puppeteer/lib/esm/puppeteer/getConfiguration.js
314028
314415
  import { homedir as homedir3 } from "os";
314029
314416
  import { join as join12 } from "path";
314030
314417
  function getBooleanEnvVar(name) {
@@ -314111,7 +314498,7 @@ var init_getConfiguration = __esm(() => {
314111
314498
  import_cosmiconfig = __toESM(require_dist12(), 1);
314112
314499
  });
314113
314500
 
314114
- // node_modules/.bun/puppeteer@24.40.0+0ec8443eac99eb1e/node_modules/puppeteer/lib/esm/puppeteer/puppeteer.js
314501
+ // node_modules/.bun/puppeteer@24.40.0+8e24a2f921b8d7be/node_modules/puppeteer/lib/esm/puppeteer/puppeteer.js
314115
314502
  var exports_puppeteer2 = {};
314116
314503
  __export(exports_puppeteer2, {
314117
314504
  withSourcePuppeteerURLIfNone: () => withSourcePuppeteerURLIfNone,
@@ -318081,6 +318468,92 @@ var init_agent_bus = __esm(() => {
318081
318468
  agentBus = new AgentBusImpl;
318082
318469
  });
318083
318470
 
318471
+ // packages/core/src/tools/agents/get-available-models.ts
318472
+ var getAvailableModelsTool;
318473
+ var init_get_available_models = __esm(() => {
318474
+ init_sqlite();
318475
+ getAvailableModelsTool = {
318476
+ name: "get_available_models",
318477
+ description: "Obtener lista de providers y modelos activos de la base de datos. Sin\xF3nimos: ver modelos, listar providers, modelos disponibles, consultar modelos, provider activo, qu\xE9 modelos tengo, modelos para c\xF3digo, modelos para chat",
318478
+ parameters: {
318479
+ type: "object",
318480
+ properties: {
318481
+ providerId: {
318482
+ type: "string",
318483
+ description: "Opcional: filtrar por provider (openai, ollama, anthropic, gemini, etc.)"
318484
+ },
318485
+ modelType: {
318486
+ type: "string",
318487
+ description: "Opcional: filtrar por tipo (llm, stt, tts, vision, embedding)"
318488
+ },
318489
+ capabilities: {
318490
+ type: "string",
318491
+ description: "Opcional: filtrar por capacidad (coding, chat, analysis, vision, reasoning)"
318492
+ }
318493
+ }
318494
+ },
318495
+ execute: async (params2) => {
318496
+ const db = getDb();
318497
+ const { providerId, modelType, capabilities } = params2;
318498
+ try {
318499
+ let query2 = `
318500
+ SELECT
318501
+ p.id as provider_id,
318502
+ p.name as provider_name,
318503
+ p.category as provider_category,
318504
+ m.id as model_id,
318505
+ m.name as model_name,
318506
+ m.model_type,
318507
+ m.context_window,
318508
+ m.capabilities
318509
+ FROM models m
318510
+ INNER JOIN providers p ON m.provider_id = p.id
318511
+ WHERE m.enabled = 1 AND m.active = 1 AND p.enabled = 1 AND p.active = 1
318512
+ `;
318513
+ const whereClauses = [];
318514
+ const queryParams = [];
318515
+ if (providerId) {
318516
+ whereClauses.push("p.id = ?");
318517
+ queryParams.push(providerId);
318518
+ }
318519
+ if (modelType) {
318520
+ whereClauses.push("m.model_type = ?");
318521
+ queryParams.push(modelType);
318522
+ }
318523
+ if (capabilities) {
318524
+ whereClauses.push("m.capabilities LIKE ?");
318525
+ queryParams.push(`%${capabilities}%`);
318526
+ }
318527
+ if (whereClauses.length > 0) {
318528
+ query2 += " AND " + whereClauses.join(" AND ");
318529
+ }
318530
+ query2 += " ORDER BY p.name, m.name";
318531
+ const rows = db.query(query2).all(...queryParams);
318532
+ const result2 = rows.map((row) => ({
318533
+ providerId: row.provider_id,
318534
+ providerName: row.provider_name,
318535
+ providerCategory: row.provider_category,
318536
+ modelId: row.model_id,
318537
+ modelName: row.model_name,
318538
+ modelType: row.model_type,
318539
+ contextWindow: row.context_window,
318540
+ capabilities: row.capabilities ? JSON.parse(row.capabilities) : null
318541
+ }));
318542
+ return {
318543
+ ok: true,
318544
+ count: result2.length,
318545
+ models: result2
318546
+ };
318547
+ } catch (error50) {
318548
+ return {
318549
+ ok: false,
318550
+ error: `Failed to get available models: ${error50.message}`
318551
+ };
318552
+ }
318553
+ }
318554
+ };
318555
+ });
318556
+
318084
318557
  // packages/core/src/tools/agents/index.ts
318085
318558
  import crypto3 from "crypto";
318086
318559
  function createTools7() {
@@ -318090,6 +318563,7 @@ function createTools7() {
318090
318563
  memoryListTool,
318091
318564
  memorySearchTool,
318092
318565
  memoryDeleteTool,
318566
+ getAvailableModelsTool,
318093
318567
  agentCreateTool,
318094
318568
  agentFindTool,
318095
318569
  agentArchiveTool,
@@ -318107,6 +318581,7 @@ var init_agents = __esm(() => {
318107
318581
  init_logger();
318108
318582
  init_agent_bus();
318109
318583
  init_emitter();
318584
+ init_get_available_models();
318110
318585
  log57 = logger.child("agents");
318111
318586
  memoryWriteTool = {
318112
318587
  name: "memory_write",
@@ -318241,16 +318716,20 @@ var init_agents = __esm(() => {
318241
318716
  };
318242
318717
  agentCreateTool = {
318243
318718
  name: "agent_create",
318244
- description: "Create a new specialized worker agent. Spanish: crear agente, nuevo worker, nuevo trabajador",
318719
+ description: "Crear un nuevo agente worker especializado. Requiere consultar get_available_models primero para seleccionar provider/model \xF3ptimos. Sin\xF3nimos: crear agente, nuevo worker, nuevo trabajador",
318245
318720
  parameters: {
318246
318721
  type: "object",
318247
318722
  properties: {
318248
- name: { type: "string", description: "Name of the agent" },
318249
- description: { type: "string", description: "Description of the agent's role" },
318250
- system_prompt: { type: "string", description: "System prompt for the agent" },
318251
- tools_json: { type: "array", description: "List of tool IDs", items: { type: "string" } }
318723
+ name: { type: "string", description: "Nombre del agente" },
318724
+ description: { type: "string", description: "Descripci\xF3n del rol del agente" },
318725
+ system_prompt: { type: "string", description: "System prompt para el agente" },
318726
+ tools_json: { type: "array", description: "Lista de IDs de herramientas", items: { type: "string" } },
318727
+ providerId: { type: "string", description: "ID del provider (openai, anthropic, ollama, etc.) - Obtener de get_available_models" },
318728
+ modelId: { type: "string", description: "ID del modelo (gpt-4o, claude-sonnet, etc.) - Obtener de get_available_models" },
318729
+ tone: { type: "string", description: "Tono del agente (friendly, professional, direct, etc.)" },
318730
+ max_iterations: { type: "number", description: "L\xEDmite de iteraciones del agente (default: 10)" }
318252
318731
  },
318253
- required: ["name"]
318732
+ required: ["name", "providerId", "modelId"]
318254
318733
  },
318255
318734
  execute: async (params2, config3) => {
318256
318735
  const db = getDb();
@@ -318260,13 +318739,56 @@ var init_agents = __esm(() => {
318260
318739
  const description = params2.description ?? "";
318261
318740
  const systemPrompt = params2.system_prompt ?? "";
318262
318741
  const toolsJson = params2.tools_json ? JSON.stringify(params2.tools_json) : null;
318742
+ const providerId = params2.providerId;
318743
+ const modelId = params2.modelId;
318744
+ const tone = params2.tone ?? "friendly";
318745
+ const maxIterations = params2.max_iterations ?? 10;
318746
+ if (!providerId || !modelId) {
318747
+ return {
318748
+ ok: false,
318749
+ error: "providerId y modelId son obligatorios. Us\xE1 get_available_models para consultar los modelos disponibles antes de crear el agente."
318750
+ };
318751
+ }
318752
+ const provider = db.query("SELECT id, name, enabled, active FROM providers WHERE id = ?").get(providerId);
318753
+ if (!provider) {
318754
+ return {
318755
+ ok: false,
318756
+ error: `Provider '${providerId}' no existe. Us\xE1 get_available_models para ver providers disponibles.`
318757
+ };
318758
+ }
318759
+ if (!provider.enabled || !provider.active) {
318760
+ return {
318761
+ ok: false,
318762
+ error: `Provider '${providerId}' no est\xE1 activo. Us\xE1 get_available_models para ver providers activos.`
318763
+ };
318764
+ }
318765
+ const model = db.query("SELECT id, name, enabled, active FROM models WHERE id = ?").get(modelId);
318766
+ if (!model) {
318767
+ return {
318768
+ ok: false,
318769
+ error: `Modelo '${modelId}' no existe. Us\xE1 get_available_models para ver modelos disponibles.`
318770
+ };
318771
+ }
318772
+ if (!model.enabled || !model.active) {
318773
+ return {
318774
+ ok: false,
318775
+ error: `Modelo '${modelId}' no est\xE1 activo. Us\xE1 get_available_models para ver modelos activos.`
318776
+ };
318777
+ }
318263
318778
  try {
318264
318779
  const agentId = crypto3.randomUUID().replace(/-/g, "").slice(0, 16);
318265
318780
  db.query(`
318266
- INSERT INTO agents (id, user_id, name, description, system_prompt, tools_json, role, status, parent_id, created_at, updated_at)
318267
- VALUES (?, ?, ?, ?, ?, ?, 'worker', 'idle', ?, unixepoch(), unixepoch())
318268
- `).run(agentId, userId, name, description, systemPrompt, toolsJson, parentId);
318269
- return { ok: true, agentId, name, message: "Agent created." };
318781
+ INSERT INTO agents (id, user_id, name, description, system_prompt, tools_json, role, status, parent_id, provider_id, model_id, tone, max_iterations, created_at, updated_at)
318782
+ VALUES (?, ?, ?, ?, ?, ?, 'worker', 'idle', ?, ?, ?, ?, ?, unixepoch(), unixepoch())
318783
+ `).run(agentId, userId, name, description, systemPrompt, toolsJson, parentId, providerId, modelId, tone, maxIterations);
318784
+ return {
318785
+ ok: true,
318786
+ agentId,
318787
+ name,
318788
+ providerId,
318789
+ modelId,
318790
+ message: "Agente creado exitosamente."
318791
+ };
318270
318792
  } catch (error50) {
318271
318793
  return { ok: false, error: `Failed to create agent: ${error50.message}` };
318272
318794
  }
@@ -318591,13 +319113,16 @@ var init_agents = __esm(() => {
318591
319113
 
318592
319114
  // packages/core/src/tools/codebridge/index.ts
318593
319115
  function createTools8() {
318594
- return [codebridgeLaunchTool, codebridgeStatusTool, codebridgeCancelTool];
319116
+ return [codebridgeLaunchTool, codebridgeStatusTool, codebridgeCancelTool, codebridgeFeedbackTool];
318595
319117
  }
318596
- var log58, CODE_BRIDGE_URL = "ws://localhost:18791/ws", codebridgeLaunchTool, codebridgeStatusTool, codebridgeCancelTool;
319118
+ var log58, CODE_BRIDGE_PORT, CODE_BRIDGE_URL, CODE_BRIDGE_BASE, codebridgeLaunchTool, codebridgeStatusTool, codebridgeCancelTool, codebridgeFeedbackTool;
318597
319119
  var init_codebridge = __esm(() => {
318598
319120
  init_logger();
318599
319121
  init_bridge_events();
318600
319122
  log58 = logger.child("codebridge");
319123
+ CODE_BRIDGE_PORT = parseInt(process.env.CODE_BRIDGE_PORT ?? "18791", 10);
319124
+ CODE_BRIDGE_URL = `ws://localhost:${CODE_BRIDGE_PORT}/ws`;
319125
+ CODE_BRIDGE_BASE = `http://localhost:${CODE_BRIDGE_PORT}`;
318601
319126
  codebridgeLaunchTool = {
318602
319127
  name: "codebridge_launch",
318603
319128
  description: "Launch an external coding CLI subagent (Claude Code, Qwen CLI, Gemini CLI, OpenCode CLI) to execute a coding task locally. Spanish: lanzar agente de c\xF3digo, iniciar Claude Code, Qwen CLI, Gemini CLI, OpenCode, subagente externo de programaci\xF3n",
@@ -318607,7 +319132,12 @@ var init_codebridge = __esm(() => {
318607
319132
  cli: {
318608
319133
  type: "string",
318609
319134
  enum: ["qwen", "claude", "opencode", "gemini"],
318610
- description: "CLI command to run"
319135
+ description: "CLI command to run (alias: agent)"
319136
+ },
319137
+ agent: {
319138
+ type: "string",
319139
+ enum: ["qwen", "claude", "opencode", "gemini"],
319140
+ description: "Alias for cli (deprecated, use cli instead)"
318611
319141
  },
318612
319142
  prompt: {
318613
319143
  type: "string",
@@ -318623,26 +319153,48 @@ var init_codebridge = __esm(() => {
318623
319153
  description: "Timeout in seconds (default: 600)"
318624
319154
  }
318625
319155
  },
318626
- required: ["cli", "prompt"]
319156
+ required: ["prompt"]
318627
319157
  },
318628
319158
  execute: async (params2) => {
318629
- const cli = params2.cli;
319159
+ const cli = params2.cli ?? params2.agent;
318630
319160
  const prompt = params2.prompt;
318631
319161
  const role = params2.role ?? "development";
318632
319162
  const timeoutSeconds = params2.timeoutSeconds ?? 600;
319163
+ if (!cli) {
319164
+ log58.error(`[codebridge_launch] \u274C Error: falta par\xE1metro 'cli' o 'agent'`);
319165
+ return {
319166
+ ok: false,
319167
+ error: "Missing required parameter: 'cli' or 'agent'. Use: codebridge_launch({ cli: 'qwen', prompt: '...' })"
319168
+ };
319169
+ }
319170
+ if (!prompt) {
319171
+ log58.error(`[codebridge_launch] \u274C Error: falta par\xE1metro 'prompt'`);
319172
+ return {
319173
+ ok: false,
319174
+ error: "Missing required parameter: 'prompt'. Use: codebridge_launch({ cli: 'qwen', prompt: '...' })"
319175
+ };
319176
+ }
319177
+ log58.info(`[codebridge_launch] Iniciando subagente ${cli} para rol: ${role}`);
319178
+ log58.info(`[codebridge_launch] Code Bridge URL: ${CODE_BRIDGE_URL}`);
319179
+ log58.info(`[codebridge_launch] Code Bridge Base: ${CODE_BRIDGE_BASE}`);
318633
319180
  try {
319181
+ log58.info(`[codebridge_launch] Verificando disponibilidad de Code Bridge...`);
318634
319182
  const controller = new AbortController;
318635
319183
  const timeout3 = setTimeout(() => controller.abort(), 1000);
318636
- const response = await fetch("http://localhost:18791/health", { signal: controller.signal });
319184
+ const response = await fetch(`${CODE_BRIDGE_BASE}/health`, { signal: controller.signal });
318637
319185
  clearTimeout(timeout3);
318638
319186
  if (!response.ok) {
319187
+ log58.error(`[codebridge_launch] Code Bridge respondi\xF3 con estado ${response.status}`);
318639
319188
  return {
318640
319189
  ok: false,
318641
319190
  error: "Code Bridge not available. Start with: bun run packages/code-bridge/src/index.ts"
318642
319191
  };
318643
319192
  }
319193
+ log58.info(`[codebridge_launch] \u2705 Code Bridge disponible`);
319194
+ log58.info(`[codebridge_launch] Conectando WebSocket a ${CODE_BRIDGE_URL}...`);
318644
319195
  const ws = new WebSocket(CODE_BRIDGE_URL);
318645
319196
  const taskId = `task_${Date.now()}`;
319197
+ log58.info(`[codebridge_launch] Task ID generado: ${taskId}`);
318646
319198
  return new Promise((resolve8) => {
318647
319199
  let resolved = false;
318648
319200
  let timeoutHandle;
@@ -318651,12 +319203,17 @@ var init_codebridge = __esm(() => {
318651
319203
  ws.close();
318652
319204
  };
318653
319205
  ws.onopen = () => {
318654
- ws.send(JSON.stringify({
319206
+ log58.info(`[codebridge_launch] \u2705 WebSocket conectado`);
319207
+ log58.info(`[codebridge_launch] Enviando comando launch para task ${taskId}...`);
319208
+ log58.info(`[codebridge_launch] Par\xE1metros: cli=${cli}, prompt=${prompt?.substring(0, 50)}..., role=${role}, timeout=${timeoutSeconds}`);
319209
+ const launchCmd = {
318655
319210
  cmd: "launch",
318656
319211
  taskId,
318657
319212
  config: { role, cli, timeoutSeconds },
318658
319213
  prompt
318659
- }));
319214
+ };
319215
+ log58.info(`[codebridge_launch] Comando JSON: ${JSON.stringify(launchCmd, null, 2).substring(0, 200)}...`);
319216
+ ws.send(JSON.stringify(launchCmd));
318660
319217
  };
318661
319218
  ws.onmessage = (event) => {
318662
319219
  let data;
@@ -318665,9 +319222,11 @@ var init_codebridge = __esm(() => {
318665
319222
  } catch {
318666
319223
  return;
318667
319224
  }
319225
+ log58.info(`[codebridge_launch] \uD83D\uDCE9 WebSocket message: ${data.type}`, data.taskId ? `task: ${data.taskId}` : "");
318668
319226
  if (data.type === "ack" && !resolved) {
318669
319227
  resolved = true;
318670
319228
  clearTimeout(timeoutHandle);
319229
+ log58.info(`[codebridge_launch] \u2705 Launch ACK recibido - PID: ${data.pid}`);
318671
319230
  emitBridgeEvent({ type: "bridge:cmd_start", data: { processId: taskId, command: cli, name: role } });
318672
319231
  resolve8({
318673
319232
  ok: true,
@@ -318682,17 +319241,21 @@ var init_codebridge = __esm(() => {
318682
319241
  if (data.type === "agent:output") {
318683
319242
  emitBridgeEvent({ type: "bridge:cmd_output", data: { processId: taskId, chunk: data.chunk, stream: data.stream ?? "stdout" } });
318684
319243
  } else if (data.type === "agent:finished") {
319244
+ log58.info(`[codebridge_launch] \u2705 Agente finalizado - Exit code: ${data.exitCode ?? 0}`);
318685
319245
  emitBridgeEvent({ type: "bridge:cmd_done", data: { processId: taskId, exitCode: data.exitCode ?? 0, success: true } });
318686
319246
  done();
318687
319247
  } else if (data.type === "agent:error") {
319248
+ log58.error(`[codebridge_launch] \u274C Error del agente: ${data.message}`);
318688
319249
  emitBridgeEvent({ type: "bridge:cmd_error", data: { processId: taskId, message: data.message } });
318689
319250
  done();
318690
319251
  } else if (data.type === "agent:cancelled") {
319252
+ log58.warn(`[codebridge_launch] \u26A0\uFE0F Agente cancelado`);
318691
319253
  emitBridgeEvent({ type: "bridge:cmd_done", data: { processId: taskId, exitCode: -1, success: false } });
318692
319254
  done();
318693
319255
  }
318694
319256
  };
318695
319257
  ws.onerror = () => {
319258
+ log58.error(`[codebridge_launch] \u274C Error de WebSocket`);
318696
319259
  if (!resolved) {
318697
319260
  resolved = true;
318698
319261
  clearTimeout(timeoutHandle);
@@ -318701,6 +319264,7 @@ var init_codebridge = __esm(() => {
318701
319264
  };
318702
319265
  timeoutHandle = setTimeout(() => {
318703
319266
  if (!resolved) {
319267
+ log58.error(`[codebridge_launch] \u23F1\uFE0F Timeout esperando respuesta de Code Bridge`);
318704
319268
  resolved = true;
318705
319269
  ws.close();
318706
319270
  resolve8({ ok: false, error: "Timeout connecting to Code Bridge" });
@@ -318708,6 +319272,7 @@ var init_codebridge = __esm(() => {
318708
319272
  }, 5000);
318709
319273
  });
318710
319274
  } catch (error50) {
319275
+ log58.error(`[codebridge_launch] \u274C Error fatal: ${error50.message}`);
318711
319276
  return {
318712
319277
  ok: false,
318713
319278
  error: `Failed to launch: ${error50.message}`
@@ -318731,7 +319296,7 @@ var init_codebridge = __esm(() => {
318731
319296
  execute: async (params2) => {
318732
319297
  const taskId = params2.taskId;
318733
319298
  try {
318734
- const response = await fetch(`http://localhost:18791/status/${taskId}`);
319299
+ const response = await fetch(`${CODE_BRIDGE_BASE}/status/${taskId}`);
318735
319300
  if (!response.ok) {
318736
319301
  return { ok: false, error: `Task not found: ${taskId}` };
318737
319302
  }
@@ -318761,7 +319326,7 @@ var init_codebridge = __esm(() => {
318761
319326
  execute: async (params2) => {
318762
319327
  const taskId = params2.taskId;
318763
319328
  try {
318764
- const response = await fetch(`http://localhost:18791/cancel/${taskId}`, { method: "POST" });
319329
+ const response = await fetch(`${CODE_BRIDGE_BASE}/cancel/${taskId}`, { method: "POST" });
318765
319330
  if (!response.ok) {
318766
319331
  return { ok: false, error: `Failed to cancel: ${taskId}` };
318767
319332
  }
@@ -318774,6 +319339,70 @@ var init_codebridge = __esm(() => {
318774
319339
  }
318775
319340
  }
318776
319341
  };
319342
+ codebridgeFeedbackTool = {
319343
+ name: "codebridge_feedback",
319344
+ description: "Send feedback or additional instructions to a running CodeBridge subagent. Use for course correction, clarifications, or iterative improvements during long-running code tasks. Spanish: enviar feedback, corregir rumbo, aclaraciones, mejoras iterativas",
319345
+ parameters: {
319346
+ type: "object",
319347
+ properties: {
319348
+ taskId: {
319349
+ type: "string",
319350
+ description: "Task ID to send feedback to"
319351
+ },
319352
+ feedback: {
319353
+ type: "string",
319354
+ description: "Feedback message or additional instructions for the running agent"
319355
+ }
319356
+ },
319357
+ required: ["taskId", "feedback"]
319358
+ },
319359
+ execute: async (params2) => {
319360
+ const taskId = params2.taskId;
319361
+ const feedback = params2.feedback;
319362
+ try {
319363
+ const ws = new WebSocket(CODE_BRIDGE_URL);
319364
+ return new Promise((resolve8) => {
319365
+ ws.onopen = () => {
319366
+ ws.send(JSON.stringify({
319367
+ cmd: "feedback",
319368
+ taskId,
319369
+ feedback
319370
+ }));
319371
+ };
319372
+ ws.onmessage = (event) => {
319373
+ try {
319374
+ const data = JSON.parse(event.data);
319375
+ if (data.type === "feedback:ack") {
319376
+ resolve8({
319377
+ ok: data.delivered,
319378
+ taskId,
319379
+ delivered: data.delivered,
319380
+ reason: data.reason,
319381
+ message: data.delivered ? "Feedback delivered to running agent" : `Feedback not delivered: ${data.reason}`
319382
+ });
319383
+ }
319384
+ } catch {
319385
+ resolve8({ ok: false, error: "Failed to parse feedback response" });
319386
+ }
319387
+ ws.close();
319388
+ };
319389
+ ws.onerror = () => {
319390
+ resolve8({ ok: false, error: "WebSocket error" });
319391
+ ws.close();
319392
+ };
319393
+ setTimeout(() => {
319394
+ resolve8({ ok: false, error: "Feedback timeout" });
319395
+ ws.close();
319396
+ }, 5000);
319397
+ });
319398
+ } catch (error50) {
319399
+ return {
319400
+ ok: false,
319401
+ error: `Failed to send feedback: ${error50.message}`
319402
+ };
319403
+ }
319404
+ }
319405
+ };
318777
319406
  });
318778
319407
 
318779
319408
  // packages/core/src/tools/voice/index.ts
@@ -319272,6 +319901,29 @@ async function compileContext(opts) {
319272
319901
  log61.info(`[context-compiler] [STEP-4] Minimal native tool set: ${filteredNativeTools.length} tools`);
319273
319902
  log61.info(`[context-compiler] [STEP-4b] MCP tools (direct): ${mcpToolsForLLM.length} tools`);
319274
319903
  log61.info(`[context-compiler] [STEP-8] \u2705 Combined tools: ${allTools.length} total, ${toolsForLLM.length} selected`);
319904
+ log61.info(`[context-compiler] [STEP-8b] Building skill loadout...`);
319905
+ let minimalSkills = [];
319906
+ let discoveredSkills = [];
319907
+ try {
319908
+ minimalSkills = getMinimalSkills();
319909
+ log61.info(`[context-compiler] [STEP-8b] \u2705 Loaded ${minimalSkills.length} minimal skills`);
319910
+ if (!isWorker) {
319911
+ discoveredSkills = selectSkills(userMessage);
319912
+ log61.info(`[context-compiler] [STEP-8b] \u2705 Discovered ${discoveredSkills.length} additional skills via FTS5`);
319913
+ }
319914
+ } catch (err) {
319915
+ log61.warn(`[context-compiler] [STEP-8b] \u26A0\uFE0F Skill loadout failed: ${err.message}`);
319916
+ }
319917
+ const skillMap = new Map;
319918
+ for (const skill of minimalSkills) {
319919
+ skillMap.set(skill.name, skill);
319920
+ }
319921
+ for (const skill of discoveredSkills) {
319922
+ if (!skillMap.has(skill.name)) {
319923
+ skillMap.set(skill.name, skill);
319924
+ }
319925
+ }
319926
+ const allSkills = Array.from(skillMap.values());
319275
319927
  log61.info(`[context-compiler] [STEP-9] Loading conversation history...`);
319276
319928
  let recentMessages = [];
319277
319929
  try {
@@ -319375,9 +320027,21 @@ ${scratchpadContent}
319375
320027
  }
319376
320028
  }
319377
320029
  if (!isWorker) {
320030
+ const minimalToolsDocs = filteredNativeTools.filter((t2) => MINIMAL_TOOLS.has(t2.name)).map((t2) => `- **${t2.name}**: ${t2.description || "Herramienta nativa"}`).join(`
320031
+ `);
319378
320032
  systemPrompt += `
319379
320033
 
319380
- # CAT\xC1LOGO DE HERRAMIENTAS
320034
+ # HERRAMIENTAS NATIVAS B\xC1SICAS (SIEMPRE DISPONIBLES)
320035
+ ` + `Estas 4 herramientas nativas est\xE1n SIEMPRE disponibles en tu contexto y tienen prioridad sobre MCP:
320036
+
320037
+ ` + `${minimalToolsDocs}
320038
+
320039
+ ` + `**REGLAS DE USO:**
320040
+ ` + `1. Si necesitas una herramienta que no est\xE9 en la lista arriba \u2192 USA primero \`search_knowledge(type="tools", query="<qu\xE9 necesitas>")\`
320041
+ ` + `2. NUNCA uses una herramienta MCP si existe una nativa equivalente en el cat\xE1logo
320042
+ ` + `3. Las MCP son fallback: \xFAsalas SOLO cuando \`search_knowledge\` NO encuentre una nativa para la tarea
320043
+
320044
+ ` + `# CAT\xC1LOGO DE HERRAMIENTAS
319381
320045
  ` + `Tienes herramientas nativas y MCP directamente disponibles.
319382
320046
  ` + `Us\xE1 \`search_knowledge\` solo para:
319383
320047
  ` + `- Skills (instrucciones de tareas complejas): type="skills"
@@ -319395,6 +320059,26 @@ ${scratchpadContent}
319395
320059
  ` + `3. El worker con esa instrucci\xF3n usar\xE1 \`search_knowledge\` para activar las tools por nombre.
319396
320060
  ` + `Ejemplo: si el worker debe investigar en internet \u2192 busca "web search herramienta internet" \u2192 obtienes "web_search" \u2192 dile al worker que use web_search.
319397
320061
  `;
320062
+ if (allSkills.length > 0) {
320063
+ let skillsSection = `
320064
+
320065
+ # SKILLS DISPONIBLES (Instrucciones de Tareas)
320066
+ `;
320067
+ skillsSection += `Estas skills est\xE1n activas para esta conversaci\xF3n. Usalas como gu\xEDa cuando sea relevante:
320068
+
320069
+ `;
320070
+ for (const skill of allSkills) {
320071
+ const isMinimal = MINIMAL_SKILL_NAMES2.includes(skill.name);
320072
+ const badge = isMinimal ? "[SIEMPRE]" : "[DISCOVERED]";
320073
+ skillsSection += `## ${skill.name} ${badge}
320074
+ `;
320075
+ skillsSection += `${skill.body.substring(0, 500)}${skill.body.length > 500 ? "..." : ""}
320076
+
320077
+ `;
320078
+ }
320079
+ systemPrompt += skillsSection;
320080
+ log61.info(`[context-compiler] [STEP-10d] Injected ${allSkills.length} skills (${minimalSkills.length} minimal, ${discoveredSkills.length} discovered)`);
320081
+ }
319398
320082
  systemPrompt += `
319399
320083
 
319400
320084
  # \uD83C\uDFA8 CANVAS A2UI \u2014 Componentes disponibles para \`canvas_render\`
@@ -319451,15 +320135,16 @@ ${opts.taskContext}
319451
320135
 
319452
320136
  Focus ONLY on this task. Do not deviate.`;
319453
320137
  }
319454
- log61.info(`[context-compiler] \u2705 DONE: ${allTools.length} total, ` + `${toolsForLLM.length} selected tools, ${messages.length} messages, ` + `isolated=${isWorker}`);
320138
+ log61.info(`[context-compiler] \u2705 DONE: ${allTools.length} total tools, ` + `${toolsForLLM.length} selected tools, ${messages.length} messages, ` + `${allSkills.length} skills (${minimalSkills.length} minimal, ${discoveredSkills.length} discovered), ` + `isolated=${isWorker}`);
319455
320139
  return {
319456
320140
  systemPrompt,
319457
320141
  messages,
319458
320142
  tools: toolsForLLM,
319459
- allTools
320143
+ allTools,
320144
+ skills: allSkills
319460
320145
  };
319461
320146
  }
319462
- var log61, KEEP_LAST_N_MESSAGES2 = 40, TOKEN_COMPACT_THRESHOLD = 6000, MINIMAL_TOOLS;
320147
+ var log61, KEEP_LAST_N_MESSAGES2 = 40, TOKEN_COMPACT_THRESHOLD = 6000, MINIMAL_TOOLS, MINIMAL_SKILL_NAMES2;
319463
320148
  var init_context_compiler = __esm(() => {
319464
320149
  init_sqlite();
319465
320150
  init_logger();
@@ -319478,6 +320163,11 @@ var init_context_compiler = __esm(() => {
319478
320163
  "report_progress",
319479
320164
  "search_knowledge"
319480
320165
  ]);
320166
+ MINIMAL_SKILL_NAMES2 = [
320167
+ "memory_manager",
320168
+ "canvas_report",
320169
+ "task_orchestrator"
320170
+ ];
319481
320171
  });
319482
320172
 
319483
320173
  // packages/core/src/agent/agent-loop.ts
@@ -319649,6 +320339,7 @@ async function* runAgent(opts) {
319649
320339
  const result2 = toolResultJS;
319650
320340
  const foundTools = result2?.tools ?? [];
319651
320341
  const currentToolNames = new Set(ctx.tools.map((t2) => t2.function?.name));
320342
+ const injectedTools = [];
319652
320343
  for (const found2 of foundTools) {
319653
320344
  if (!currentToolNames.has(found2.name)) {
319654
320345
  const nativeTool = ctx.allTools.find((t2) => t2.name === found2.name);
@@ -319663,7 +320354,50 @@ async function* runAgent(opts) {
319663
320354
  });
319664
320355
  log62.info(`[agent-loop] Injected discovered native tool into loadout: ${nativeTool.name}`);
319665
320356
  currentToolNames.add(found2.name);
320357
+ injectedTools.push(nativeTool.name);
320358
+ }
320359
+ }
320360
+ }
320361
+ if (injectedTools.length > 0) {
320362
+ try {
320363
+ const db2 = getDb();
320364
+ const placeholders = injectedTools.map(() => "?").join(",");
320365
+ const skillsWithTools = db2.query(`
320366
+ SELECT DISTINCT s.name, s.body, s.tools
320367
+ FROM skills s
320368
+ WHERE s.active = 1
320369
+ AND (
320370
+ ${injectedTools.map(() => `s.tools LIKE ?`).join(" OR ")}
320371
+ )
320372
+ `).all(...injectedTools.map((t2) => `%${t2}%`));
320373
+ const matchingSkills = skillsWithTools.filter((s2) => {
320374
+ const skillTools = s2.tools?.split(",").map((t2) => t2.trim()) ?? [];
320375
+ return injectedTools.some((injected) => skillTools.includes(injected));
320376
+ });
320377
+ if (matchingSkills.length > 0) {
320378
+ const skillSection = matchingSkills.map((s2) => `## Skill: ${s2.name}
320379
+ ${s2.body}`).join(`
320380
+
320381
+ `);
320382
+ const systemMsg = messages.find((m2) => m2.role === "system");
320383
+ if (systemMsg && typeof systemMsg.content === "string") {
320384
+ const existingSkillNames = new Set((systemMsg.content.match(/## Skill: ([^\n]+)/g) || []).map((m2) => m2.replace("## Skill: ", "").trim()));
320385
+ const newSkills = matchingSkills.filter((s2) => !existingSkillNames.has(s2.name));
320386
+ if (newSkills.length > 0) {
320387
+ const newSkillSection = newSkills.map((s2) => `## Skill: ${s2.name}
320388
+ ${s2.body}`).join(`
320389
+
320390
+ `);
320391
+ systemMsg.content += `
320392
+
320393
+ --- SKILL INSTRUCTIONS (Auto-loaded) ---
320394
+ ${newSkillSection}`;
320395
+ log62.info(`[agent-loop] Injected ${newSkills.length} skill(s) for tools: ${newSkills.map((s2) => s2.name).join(", ")}`);
320396
+ }
320397
+ }
319666
320398
  }
320399
+ } catch (skillErr) {
320400
+ log62.warn(`[agent-loop] Failed to inject skills for tools: ${skillErr.message}`);
319667
320401
  }
319668
320402
  }
319669
320403
  } catch (err) {
@@ -546002,7 +546736,7 @@ var init_v4_mini = __esm(() => {
546002
546736
  init_external2();
546003
546737
  });
546004
546738
 
546005
- // node_modules/.bun/@modelcontextprotocol+sdk@1.27.1/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
546739
+ // node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
546006
546740
  function isZ4Schema(s2) {
546007
546741
  const schema2 = s2;
546008
546742
  return !!schema2._zod;
@@ -546078,7 +546812,7 @@ var init_v4 = __esm(() => {
546078
546812
  init_classic();
546079
546813
  });
546080
546814
 
546081
- // node_modules/.bun/@modelcontextprotocol+sdk@1.27.1/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
546815
+ // node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
546082
546816
  var LATEST_PROTOCOL_VERSION = "2025-11-25", SUPPORTED_PROTOCOL_VERSIONS, RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task", JSONRPC_VERSION = "2.0", AssertObjectSchema, ProgressTokenSchema, CursorSchema, TaskCreationParamsSchema, TaskMetadataSchema, RelatedTaskMetadataSchema, RequestMetaSchema, BaseRequestParamsSchema, TaskAugmentedRequestParamsSchema, isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success, RequestSchema, NotificationsParamsSchema, NotificationSchema, ResultSchema, RequestIdSchema, JSONRPCRequestSchema, isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success, JSONRPCNotificationSchema, isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success, JSONRPCResultResponseSchema, isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success, ErrorCode, JSONRPCErrorResponseSchema, isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success, JSONRPCMessageSchema, JSONRPCResponseSchema, EmptyResultSchema, CancelledNotificationParamsSchema, CancelledNotificationSchema, IconSchema, IconsSchema, BaseMetadataSchema, ImplementationSchema, FormElicitationCapabilitySchema, ElicitationCapabilitySchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema, ClientCapabilitiesSchema, InitializeRequestParamsSchema, InitializeRequestSchema, ServerCapabilitiesSchema, InitializeResultSchema, InitializedNotificationSchema, PingRequestSchema, ProgressSchema, ProgressNotificationParamsSchema, ProgressNotificationSchema, PaginatedRequestParamsSchema, PaginatedRequestSchema, PaginatedResultSchema, TaskStatusSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, GetTaskPayloadResultSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ResourceContentsSchema, TextResourceContentsSchema, Base64Schema, BlobResourceContentsSchema, RoleSchema, AnnotationsSchema, ResourceSchema, ResourceTemplateSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ResourceRequestParamsSchema, ReadResourceRequestParamsSchema, ReadResourceRequestSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, SubscribeRequestParamsSchema, SubscribeRequestSchema, UnsubscribeRequestParamsSchema, UnsubscribeRequestSchema, ResourceUpdatedNotificationParamsSchema, ResourceUpdatedNotificationSchema, PromptArgumentSchema, PromptSchema, ListPromptsRequestSchema, ListPromptsResultSchema, GetPromptRequestParamsSchema, GetPromptRequestSchema, TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, EmbeddedResourceSchema, ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ToolAnnotationsSchema, ToolExecutionSchema, ToolSchema, ListToolsRequestSchema, ListToolsResultSchema, CallToolResultSchema, CompatibilityCallToolResultSchema, CallToolRequestParamsSchema, CallToolRequestSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, LoggingLevelSchema, SetLevelRequestParamsSchema, SetLevelRequestSchema, LoggingMessageNotificationParamsSchema, LoggingMessageNotificationSchema, ModelHintSchema, ModelPreferencesSchema, ToolChoiceSchema, ToolResultContentSchema, SamplingContentSchema, SamplingMessageContentBlockSchema, SamplingMessageSchema, CreateMessageRequestParamsSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema, LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema, EnumSchemaSchema, PrimitiveSchemaDefinitionSchema, ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema, ElicitRequestParamsSchema, ElicitRequestSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, ElicitResultSchema, ResourceTemplateReferenceSchema, PromptReferenceSchema, CompleteRequestParamsSchema, CompleteRequestSchema, CompleteResultSchema, RootSchema, ListRootsRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, ClientRequestSchema, ClientNotificationSchema, ClientResultSchema, ServerRequestSchema, ServerNotificationSchema, ServerResultSchema, McpError, UrlElicitationRequiredError;
546083
546817
  var init_types7 = __esm(() => {
546084
546818
  init_v4();
@@ -546087,7 +546821,7 @@ var init_types7 = __esm(() => {
546087
546821
  ProgressTokenSchema = union([string2(), number2().int()]);
546088
546822
  CursorSchema = string2();
546089
546823
  TaskCreationParamsSchema = looseObject({
546090
- ttl: union([number2(), _null3()]).optional(),
546824
+ ttl: number2().optional(),
546091
546825
  pollInterval: number2().optional()
546092
546826
  });
546093
546827
  TaskMetadataSchema = object({
@@ -546235,7 +546969,8 @@ var init_types7 = __esm(() => {
546235
546969
  roots: object({
546236
546970
  listChanged: boolean2().optional()
546237
546971
  }).optional(),
546238
- tasks: ClientTasksCapabilitySchema.optional()
546972
+ tasks: ClientTasksCapabilitySchema.optional(),
546973
+ extensions: record(string2(), AssertObjectSchema).optional()
546239
546974
  });
546240
546975
  InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
546241
546976
  protocolVersion: string2(),
@@ -546260,7 +546995,8 @@ var init_types7 = __esm(() => {
546260
546995
  tools: object({
546261
546996
  listChanged: boolean2().optional()
546262
546997
  }).optional(),
546263
- tasks: ServerTasksCapabilitySchema.optional()
546998
+ tasks: ServerTasksCapabilitySchema.optional(),
546999
+ extensions: record(string2(), AssertObjectSchema).optional()
546264
547000
  });
546265
547001
  InitializeResultSchema = ResultSchema.extend({
546266
547002
  protocolVersion: string2(),
@@ -546375,6 +547111,7 @@ var init_types7 = __esm(() => {
546375
547111
  uri: string2(),
546376
547112
  description: optional(string2()),
546377
547113
  mimeType: optional(string2()),
547114
+ size: optional(number2()),
546378
547115
  annotations: AnnotationsSchema.optional(),
546379
547116
  _meta: optional(looseObject({}))
546380
547117
  });
@@ -546903,7 +547640,7 @@ var init_types7 = __esm(() => {
546903
547640
  };
546904
547641
  });
546905
547642
 
546906
- // node_modules/.bun/@modelcontextprotocol+sdk@1.27.1/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
547643
+ // node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
546907
547644
  function isTerminal(status) {
546908
547645
  return status === "completed" || status === "failed" || status === "cancelled";
546909
547646
  }
@@ -547121,7 +547858,7 @@ var init_esm2 = __esm(() => {
547121
547858
  init_zodToJsonSchema();
547122
547859
  });
547123
547860
 
547124
- // node_modules/.bun/@modelcontextprotocol+sdk@1.27.1/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
547861
+ // node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
547125
547862
  function getMethodLiteral(schema2) {
547126
547863
  const shape = getObjectShape(schema2);
547127
547864
  const methodSchema = shape?.method;
@@ -547146,7 +547883,7 @@ var init_zod_json_schema_compat = __esm(() => {
547146
547883
  init_esm2();
547147
547884
  });
547148
547885
 
547149
- // node_modules/.bun/@modelcontextprotocol+sdk@1.27.1/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
547886
+ // node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
547150
547887
  class Protocol {
547151
547888
  constructor(_options) {
547152
547889
  this._options = _options;
@@ -547348,6 +548085,10 @@ class Protocol {
547348
548085
  this._progressHandlers.clear();
547349
548086
  this._taskProgressTokens.clear();
547350
548087
  this._pendingDebouncedNotifications.clear();
548088
+ for (const info of this._timeoutInfo.values()) {
548089
+ clearTimeout(info.timeoutId);
548090
+ }
548091
+ this._timeoutInfo.clear();
547351
548092
  for (const controller of this._requestHandlerAbortControllers.values()) {
547352
548093
  controller.abort();
547353
548094
  }
@@ -547478,7 +548219,9 @@ class Protocol {
547478
548219
  await capturedTransport?.send(errorResponse);
547479
548220
  }
547480
548221
  }).catch((error50) => this._onerror(new Error(`Failed to send response: ${error50}`))).finally(() => {
547481
- this._requestHandlerAbortControllers.delete(request3.id);
548222
+ if (this._requestHandlerAbortControllers.get(request3.id) === abortController) {
548223
+ this._requestHandlerAbortControllers.delete(request3.id);
548224
+ }
547482
548225
  });
547483
548226
  }
547484
548227
  _onprogress(notification) {
@@ -554415,7 +555158,7 @@ var require_dist29 = __commonJS((exports2, module2) => {
554415
555158
  exports2.default = formatsPlugin;
554416
555159
  });
554417
555160
 
554418
- // node_modules/.bun/@modelcontextprotocol+sdk@1.27.1/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
555161
+ // node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
554419
555162
  function createDefaultAjvInstance() {
554420
555163
  const ajv = new import_ajv.default({
554421
555164
  strict: false,
@@ -554458,7 +555201,7 @@ var init_ajv_provider = __esm(() => {
554458
555201
  import_ajv_formats = __toESM(require_dist29(), 1);
554459
555202
  });
554460
555203
 
554461
- // node_modules/.bun/@modelcontextprotocol+sdk@1.27.1/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
555204
+ // node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
554462
555205
  class ExperimentalClientTasks {
554463
555206
  constructor(_client) {
554464
555207
  this._client = _client;
@@ -554527,7 +555270,7 @@ var init_client3 = __esm(() => {
554527
555270
  init_types7();
554528
555271
  });
554529
555272
 
554530
- // node_modules/.bun/@modelcontextprotocol+sdk@1.27.1/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
555273
+ // node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
554531
555274
  function assertToolsCallTaskCapability(requests2, method, entityName) {
554532
555275
  if (!requests2) {
554533
555276
  throw new Error(`${entityName} does not support task creation (required for ${method})`);
@@ -554562,7 +555305,7 @@ function assertClientRequestTaskCapability(requests2, method, entityName) {
554562
555305
  }
554563
555306
  }
554564
555307
 
554565
- // node_modules/.bun/@modelcontextprotocol+sdk@1.27.1/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
555308
+ // node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
554566
555309
  function applyElicitationDefaults(schema2, data) {
554567
555310
  if (!schema2 || data === null || typeof data !== "object")
554568
555311
  return;
@@ -555534,7 +556277,7 @@ var require_cross_spawn = __commonJS((exports2, module2) => {
555534
556277
  module2.exports._enoent = enoent;
555535
556278
  });
555536
556279
 
555537
- // node_modules/.bun/@modelcontextprotocol+sdk@1.27.1/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
556280
+ // node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
555538
556281
  class ReadBuffer {
555539
556282
  append(chunk2) {
555540
556283
  this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk2]) : chunk2;
@@ -555567,7 +556310,7 @@ var init_stdio = __esm(() => {
555567
556310
  init_types7();
555568
556311
  });
555569
556312
 
555570
- // node_modules/.bun/@modelcontextprotocol+sdk@1.27.1/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
556313
+ // node_modules/.bun/@modelcontextprotocol+sdk@1.29.0/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
555571
556314
  import process4 from "process";
555572
556315
  import { PassThrough as PassThrough2 } from "stream";
555573
556316
  function getDefaultEnvironment() {
@@ -555606,7 +556349,7 @@ class StdioClientTransport {
555606
556349
  },
555607
556350
  stdio: ["pipe", "pipe", this._serverParams.stderr ?? "inherit"],
555608
556351
  shell: false,
555609
- windowsHide: process4.platform === "win32" && isElectron(),
556352
+ windowsHide: process4.platform === "win32",
555610
556353
  cwd: this._serverParams.cwd
555611
556354
  });
555612
556355
  this._process.on("error", (error50) => {
@@ -555698,9 +556441,6 @@ class StdioClientTransport {
555698
556441
  });
555699
556442
  }
555700
556443
  }
555701
- function isElectron() {
555702
- return "type" in process4;
555703
- }
555704
556444
  var import_cross_spawn, DEFAULT_INHERITED_ENV_VARS;
555705
556445
  var init_stdio2 = __esm(() => {
555706
556446
  init_stdio();
@@ -556928,7 +557668,7 @@ async function handleCompleteSetup(req, config3, addCorsHeaders) {
556928
557668
  userId,
556929
557669
  agentName: body.agentName || "Bee",
556930
557670
  description: body.agentDescription || "",
556931
- tone: "friendly",
557671
+ tone: body.agentTone || "friendly",
556932
557672
  providerId: body.provider || "",
556933
557673
  modelId: body.model || ""
556934
557674
  });
@@ -557097,9 +557837,13 @@ async function handleDisableAuth(req, cors) {
557097
557837
  getDb().query(`UPDATE users SET email = NULL, password_hash = NULL`).run();
557098
557838
  return cors(Response.json({ success: true }), req);
557099
557839
  }
557840
+ var import_jsonwebtoken, JWT_SECRET, ACCESS_TOKEN_EXPIRY_SECONDS;
557100
557841
  var init_auth = __esm(() => {
557101
557842
  init_sqlite();
557102
557843
  init_loader();
557844
+ import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1);
557845
+ JWT_SECRET = process.env.HIVE_JWT_SECRET || process.env.HIVE_AUTH_TOKEN || "hive-default-jwt-secret-change-in-production";
557846
+ ACCESS_TOKEN_EXPIRY_SECONDS = 15 * 60;
557103
557847
  });
557104
557848
 
557105
557849
  // packages/core/src/gateway/routes/agents.ts
@@ -558536,7 +559280,7 @@ var package_default;
558536
559280
  var init_package = __esm(() => {
558537
559281
  package_default = {
558538
559282
  name: "@johpaz/hive-agents-core",
558539
- version: "0.0.8",
559283
+ version: "0.0.11",
558540
559284
  private: true,
558541
559285
  description: "Hive Gateway \u2014 Personal AI agent runtime",
558542
559286
  main: "./src/index.ts",
@@ -558552,9 +559296,9 @@ var init_package = __esm(() => {
558552
559296
  },
558553
559297
  dependencies: {
558554
559298
  "@ag-ui/core": "^0.0.46",
558555
- "@johpaz/hive-agents-code-bridge": "^0.0.8",
558556
- "@johpaz/hive-agents-mcp": "^0.0.8",
558557
- "@johpaz/hive-agents-skills": "^0.0.8",
559299
+ "@johpaz/hive-agents-code-bridge": "^0.0.11",
559300
+ "@johpaz/hive-agents-mcp": "^0.0.11",
559301
+ "@johpaz/hive-agents-skills": "^0.0.11",
558558
559302
  "@modelcontextprotocol/sdk": "latest",
558559
559303
  "@sapphire/snowflake": "latest",
558560
559304
  "@slack/bolt": "latest",
@@ -558569,7 +559313,7 @@ var init_package = __esm(() => {
558569
559313
  zod: "latest"
558570
559314
  },
558571
559315
  devDependencies: {
558572
- typescript: "6.0.1-rc",
559316
+ typescript: "6.0.2",
558573
559317
  "@types/bun": "latest"
558574
559318
  },
558575
559319
  exports: {
@@ -558613,6 +559357,7 @@ var init_package = __esm(() => {
558613
559357
  "./tools/projects": "./src/tools/projects/index.ts",
558614
559358
  "./tools/voice": "./src/tools/voice/index.ts",
558615
559359
  "./tools/web": "./src/tools/web/index.ts",
559360
+ "./tools/schedule": "./src/tools/schedule.ts",
558616
559361
  "./integrations": "./src/integrations/index.ts",
558617
559362
  "./integrations/catalog": "./src/integrations/catalog.ts",
558618
559363
  "./integrations/env": "./src/integrations/env.ts",
@@ -560647,7 +561392,7 @@ ${messageContent}`;
560647
561392
  });
560648
561393
  }
560649
561394
  });
560650
- const isDev = process.env.HIVE_DEV === "true" && existsSync18(path32.join(process.cwd(), "packages/hive-ui/package.json"));
561395
+ const isDev = process.env.HIVE_DEV === "true" || process.env.HIVE_DEV === "1";
560651
561396
  function checkAuth(req, url3) {
560652
561397
  if (isDev)
560653
561398
  return true;
@@ -560661,6 +561406,14 @@ ${messageContent}`;
560661
561406
  return true;
560662
561407
  if (url3.pathname === "/api/auth/recover")
560663
561408
  return true;
561409
+ if (url3.pathname === "/api/users" && req.method === "GET") {
561410
+ try {
561411
+ const user = getDb().query(`SELECT email, password_hash FROM users LIMIT 1`).get();
561412
+ const hasCredentials = !!(user?.email && user?.password_hash);
561413
+ if (!hasCredentials)
561414
+ return true;
561415
+ } catch {}
561416
+ }
560664
561417
  const activeToken = process.env.HIVE_AUTH_TOKEN;
560665
561418
  if (!activeToken)
560666
561419
  return true;
@@ -560743,10 +561496,43 @@ ${messageContent}`;
560743
561496
  const isSetupRequest = url3.pathname === "/setup" || url3.pathname === "/setup/" || url3.pathname.startsWith("/setup/") || url3.pathname.startsWith("/setup?");
560744
561497
  if (!isApiRequest && !isWsRequest) {
560745
561498
  if (isDev) {
560746
- return new Response(`UI not available through Gateway in development.
560747
-
560748
- ` + `Use Vite directly: http://localhost:5173
560749
- `, { status: 404, headers: { "Content-Type": "text/plain" } });
561499
+ const uiDir2 = path32.join(process.cwd(), "packages/hive-ui/dist");
561500
+ const indexPath = path32.join(uiDir2, "index.html");
561501
+ if (!existsSync18(indexPath)) {
561502
+ return new Response(`UI build not found. Please run: cd packages/hive-ui && bun run build
561503
+
561504
+ ` + "Or use: bun run dev (from root) which builds automatically.", { status: 503, headers: { "Content-Type": "text/plain" } });
561505
+ }
561506
+ let subPath2 = url3.pathname;
561507
+ if (subPath2 === "/" || subPath2 === "/setup" || subPath2 === "/ui" || subPath2 === "/ui/") {
561508
+ subPath2 = "/index.html";
561509
+ } else if (subPath2.startsWith("/ui/")) {
561510
+ subPath2 = subPath2.replace(/^\/ui/, "");
561511
+ } else if (subPath2.startsWith("/setup/")) {
561512
+ subPath2 = subPath2.replace(/^\/setup/, "");
561513
+ }
561514
+ const filePath2 = path32.join(uiDir2, subPath2);
561515
+ if (subPath2 === "/index.html") {
561516
+ const indexFile = Bun.file(filePath2);
561517
+ if (await indexFile.exists()) {
561518
+ let html = await indexFile.text();
561519
+ const hmrScript = `<script type="module" src="http://localhost:5173/@vite/client"></script>`;
561520
+ html = html.replace("</head>", `${hmrScript}</head>`);
561521
+ return new Response(html, { headers: { "Content-Type": "text/html" } });
561522
+ }
561523
+ }
561524
+ const uiFile2 = Bun.file(filePath2);
561525
+ if (await uiFile2.exists()) {
561526
+ return new Response(uiFile2);
561527
+ }
561528
+ const fallbackFile = Bun.file(path32.join(uiDir2, "index.html"));
561529
+ if (await fallbackFile.exists()) {
561530
+ let html = await fallbackFile.text();
561531
+ const hmrScript = `<script type="module" src="http://localhost:5173/@vite/client"></script>`;
561532
+ html = html.replace("</head>", `${hmrScript}</head>`);
561533
+ return new Response(html, { headers: { "Content-Type": "text/html" } });
561534
+ }
561535
+ return new Response("Not found", { status: 404 });
560750
561536
  }
560751
561537
  const uiDirFromEnv = process.env.HIVE_UI_DIR;
560752
561538
  const uiDirFromHive = path32.join(getHiveDir(), "ui");
@@ -561417,7 +562203,7 @@ ${messageContent}`;
561417
562203
  const codeBridge = db.query("SELECT id FROM code_bridge WHERE enabled = 1").all();
561418
562204
  ws.send(JSON.stringify({
561419
562205
  type: "welcome",
561420
- sessionId: user?.id || data.sessionId,
562206
+ sessionId: data.sessionId,
561421
562207
  user: user ? { id: user.id, name: user.name, language: user.language } : null,
561422
562208
  agent: agent2 ? { id: agent2.id, name: agent2.name, provider: agent2.provider_id, model: agent2.model_id } : null,
561423
562209
  channels: channels.map((c3) => c3.id),
@@ -561887,12 +562673,14 @@ ${messageContent}`;
561887
562673
  log70.info(`Gateway started successfully`);
561888
562674
  const isGatewayChild = process.env.HIVE_GATEWAY_CHILD === "1";
561889
562675
  if (isDev) {
562676
+ const devUrl = gatewaySetupMode ? `http://localhost:${port}/setup` : `http://localhost:${port}`;
562677
+ log70.info(`[gateway] UI: ${devUrl}`);
561890
562678
  log70.info(`[gateway] API: http://${host}:${port}`);
561891
562679
  log70.info(`[gateway] WebSocket: ws://${host}:${port}/ws`);
561892
562680
  log70.info(`[gateway] Canvas: ws://${host}:${port}/canvas`);
561893
562681
  log70.info(`[gateway] Modo: desarrollo`);
561894
562682
  if (!isGatewayChild) {
561895
- log70.info(`\uD83D\uDC1D Administra tu Hive aqu\xED: http://localhost:5173`);
562683
+ log70.info(gatewaySetupMode ? `\uD83C\uDF89 Primer arranque \u2014 abriendo setup...` : `\uD83D\uDC1D Administra tu Hive aqu\xED: ${devUrl}`);
561896
562684
  }
561897
562685
  } else {
561898
562686
  const isSetupMode2 = gatewaySetupMode;
@@ -563954,7 +564742,7 @@ function getDistDir() {
563954
564742
  return null;
563955
564743
  }
563956
564744
  function isDevMode() {
563957
- return process.env.HIVE_DEV === "true" && existsSync20(path34.join(process.cwd(), "packages/hive-ui/package.json"));
564745
+ return process.env.HIVE_DEV === "true" || process.env.HIVE_DEV === "1";
563958
564746
  }
563959
564747
  function isChildProcess() {
563960
564748
  return process.env.HIVE_GATEWAY_CHILD === "1";
@@ -564245,7 +565033,7 @@ class BunGlobalAdapter {
564245
565033
  },
564246
565034
  paths,
564247
565035
  env: env3,
564248
- isDev: process.env.HIVE_DEV === "true",
565036
+ isDev: process.env.HIVE_DEV === "true" || process.env.HIVE_DEV === "1",
564249
565037
  hasEmbeddedUI: false
564250
565038
  };
564251
565039
  }
@@ -564816,6 +565604,120 @@ var init_adapters = __esm(() => {
564816
565604
  init_factory();
564817
565605
  });
564818
565606
 
565607
+ // packages/code-bridge/src/cli-configs.ts
565608
+ function getCliConfig(cliName) {
565609
+ const normalized = cliName.toLowerCase().trim();
565610
+ return CLI_CONFIGS[normalized];
565611
+ }
565612
+ function buildCliArgs(cliName, extraArgs = []) {
565613
+ const config4 = getCliConfig(cliName);
565614
+ if (!config4) {
565615
+ return extraArgs;
565616
+ }
565617
+ const args = [...config4.defaultArgs];
565618
+ for (const arg of extraArgs) {
565619
+ if (!args.includes(arg)) {
565620
+ args.push(arg);
565621
+ }
565622
+ }
565623
+ return args;
565624
+ }
565625
+ function validateCliEnv(cliName) {
565626
+ const config4 = getCliConfig(cliName);
565627
+ if (!config4) {
565628
+ return { valid: true, missing: [] };
565629
+ }
565630
+ const missing = [];
565631
+ for (const envVar of config4.envVars) {
565632
+ if (!process.env[envVar]) {
565633
+ missing.push(envVar);
565634
+ }
565635
+ }
565636
+ return {
565637
+ valid: missing.length === 0,
565638
+ missing
565639
+ };
565640
+ }
565641
+ function getCliTimeout(cliName, override) {
565642
+ if (override !== undefined) {
565643
+ return override;
565644
+ }
565645
+ const config4 = getCliConfig(cliName);
565646
+ return config4?.timeoutSeconds ?? 120;
565647
+ }
565648
+ function requiresStdinClose(cliName) {
565649
+ const config4 = getCliConfig(cliName);
565650
+ return config4?.requiresStdinClose ?? false;
565651
+ }
565652
+ var CLI_CONFIGS;
565653
+ var init_cli_configs = __esm(() => {
565654
+ CLI_CONFIGS = {
565655
+ claude: {
565656
+ cmd: "claude",
565657
+ defaultArgs: ["--no-approve", "--output-format", "stream"],
565658
+ envVars: ["ANTHROPIC_API_KEY"],
565659
+ timeoutSeconds: 300,
565660
+ requiresStdinClose: false,
565661
+ approvalFlag: "--no-approve",
565662
+ description: "Anthropic's Claude Code CLI - Best for complex architecture and refactoring",
565663
+ useCases: [
565664
+ "Code architecture and design",
565665
+ "Complex refactoring tasks",
565666
+ "Security-focused code review",
565667
+ "Documentation generation"
565668
+ ]
565669
+ },
565670
+ qwen: {
565671
+ cmd: "qwen",
565672
+ defaultArgs: ["--yolo"],
565673
+ envVars: [],
565674
+ timeoutSeconds: 300,
565675
+ requiresStdinClose: false,
565676
+ approvalFlag: "--yolo",
565677
+ headlessFlag: "-p",
565678
+ description: "Alibaba's Qwen CLI - Fast code generation and debugging",
565679
+ useCases: [
565680
+ "Quick code generation",
565681
+ "Bug fixes and debugging",
565682
+ "Utility functions",
565683
+ "Boilerplate code"
565684
+ ]
565685
+ },
565686
+ gemini: {
565687
+ cmd: "gemini",
565688
+ defaultArgs: ["-y", "--quiet"],
565689
+ envVars: ["GOOGLE_API_KEY"],
565690
+ timeoutSeconds: 240,
565691
+ requiresStdinClose: false,
565692
+ approvalFlag: "-y",
565693
+ headlessFlag: "--no-interactive",
565694
+ description: "Google's Gemini CLI - Balanced code generation with documentation",
565695
+ useCases: [
565696
+ "Code + documentation pairs",
565697
+ "Multi-language projects",
565698
+ "API integration code",
565699
+ "Test generation"
565700
+ ]
565701
+ },
565702
+ opencode: {
565703
+ cmd: "opencode",
565704
+ defaultArgs: ["--headless", "--auto-accept"],
565705
+ envVars: [],
565706
+ timeoutSeconds: 200,
565707
+ requiresStdinClose: false,
565708
+ approvalFlag: "--auto-accept",
565709
+ headlessFlag: "--headless",
565710
+ description: "OpenCode CLI - Flexible, open source focused",
565711
+ useCases: [
565712
+ "Open source project scaffolding",
565713
+ "Multi-language support",
565714
+ "Community-driven patterns",
565715
+ "Rapid prototyping"
565716
+ ]
565717
+ }
565718
+ };
565719
+ });
565720
+
564819
565721
  // packages/code-bridge/src/process-manager.ts
564820
565722
  class ProcessManager {
564821
565723
  agents = new Map;
@@ -564840,13 +565742,34 @@ class ProcessManager {
564840
565742
  if (this.agents.has(taskId)) {
564841
565743
  throw new Error(`Task ${taskId} is already running`);
564842
565744
  }
564843
- const args = [config4.cli, ...config4.args];
565745
+ const cliConfig = getCliConfig(config4.cli);
565746
+ const envValidation = validateCliEnv(config4.cli);
565747
+ if (!envValidation.valid) {
565748
+ throw new Error(`Missing environment variables for ${config4.cli}: ${envValidation.missing.join(", ")}`);
565749
+ }
565750
+ const cliArgs = buildCliArgs(config4.cli, config4.args);
565751
+ const args = [config4.cli, ...cliArgs];
565752
+ const timeoutSeconds = getCliTimeout(config4.cli, config4.timeoutSeconds);
565753
+ const shouldCloseStdin = requiresStdinClose(config4.cli);
565754
+ const isQwen = config4.cli === "qwen";
565755
+ if (isQwen && prompt) {
565756
+ args.push("-p", prompt);
565757
+ }
564844
565758
  const proc = Bun.spawn(args, {
564845
565759
  cwd: config4.cwd ?? process.cwd(),
564846
- stdin: "pipe",
565760
+ stdin: isQwen ? "ignore" : "pipe",
564847
565761
  stdout: "pipe",
564848
565762
  stderr: "pipe",
564849
- env: { ...process.env, HIVE_ROLE: config4.role }
565763
+ env: {
565764
+ ...process.env,
565765
+ HIVE_ROLE: config4.role,
565766
+ ...cliConfig?.envVars.reduce((acc, key) => {
565767
+ if (process.env[key]) {
565768
+ acc[key] = process.env[key];
565769
+ }
565770
+ return acc;
565771
+ }, {}) ?? {}
565772
+ }
564850
565773
  });
564851
565774
  const record3 = {
564852
565775
  taskId,
@@ -564867,8 +565790,12 @@ class ProcessManager {
564867
565790
  cli: config4.cli,
564868
565791
  taskId
564869
565792
  });
564870
- proc.stdin.write(prompt);
564871
- proc.stdin.end();
565793
+ if (!isQwen) {
565794
+ proc.stdin.write(prompt);
565795
+ if (shouldCloseStdin) {
565796
+ proc.stdin.end();
565797
+ }
565798
+ }
564872
565799
  this.pipeStream(record3, proc.stdout, "stdout");
564873
565800
  this.pipeStream(record3, proc.stderr, "stderr");
564874
565801
  proc.exited.then((exitCode) => {
@@ -564926,6 +565853,24 @@ class ProcessManager {
564926
565853
  }))
564927
565854
  };
564928
565855
  }
565856
+ statusForTask(taskId) {
565857
+ const record3 = this.agents.get(taskId);
565858
+ if (!record3) {
565859
+ return { found: false, taskId };
565860
+ }
565861
+ return {
565862
+ found: true,
565863
+ taskId: record3.taskId,
565864
+ role: record3.config.role,
565865
+ cli: record3.config.cli,
565866
+ pid: record3.pid,
565867
+ state: record3.state,
565868
+ progress: record3.progress,
565869
+ tokens: record3.tokens,
565870
+ model: record3.model,
565871
+ startedAt: record3.startedAt
565872
+ };
565873
+ }
564929
565874
  async pipeStream(record3, stream, kind) {
564930
565875
  const reader = stream.getReader();
564931
565876
  const decoder = new TextDecoder;
@@ -564976,6 +565921,9 @@ class ProcessManager {
564976
565921
  } catch {}
564977
565922
  }
564978
565923
  }
565924
+ var init_process_manager = __esm(() => {
565925
+ init_cli_configs();
565926
+ });
564979
565927
 
564980
565928
  // packages/code-bridge/src/schemas.ts
564981
565929
  var AgentRole, SubagentConfig, TelemetryEventType, BaseEvent, AgentStartedEvent, AgentOutputEvent, AgentProgressEvent, AgentTokenUsageEvent, AgentFinishedEvent, AgentErrorEvent, AgentCancelledEvent, CodeBridgeStatusEvent, TelemetryEvent, DashboardCommand;
@@ -565079,30 +566027,38 @@ var init_schemas4 = __esm(() => {
565079
566027
  }),
565080
566028
  exports_external.object({ cmd: exports_external.literal("cancel"), taskId: exports_external.string() }),
565081
566029
  exports_external.object({ cmd: exports_external.literal("status") }),
565082
- exports_external.object({ cmd: exports_external.literal("ping") })
566030
+ exports_external.object({ cmd: exports_external.literal("ping") }),
566031
+ exports_external.object({
566032
+ cmd: exports_external.literal("feedback"),
566033
+ taskId: exports_external.string(),
566034
+ feedback: exports_external.string()
566035
+ })
565083
566036
  ]);
565084
566037
  });
565085
566038
 
565086
566039
  // packages/code-bridge/src/index.ts
565087
566040
  var exports_src = {};
565088
- var CODE_BRIDGE_PORT, manager4, server3;
566041
+ var CODE_BRIDGE_PORT2, HEARTBEAT_INTERVAL = 30000, HEARTBEAT_TIMEOUT = 45000, manager4, server3;
565089
566042
  var init_src4 = __esm(() => {
566043
+ init_process_manager();
565090
566044
  init_schemas4();
565091
- CODE_BRIDGE_PORT = parseInt(process.env.CODE_BRIDGE_PORT ?? "18791", 10);
566045
+ CODE_BRIDGE_PORT2 = parseInt(process.env.CODE_BRIDGE_PORT ?? "18791", 10);
565092
566046
  manager4 = new ProcessManager;
566047
+ console.log(`\uD83C\uDF09 [Code Bridge] Iniciando servidor en puerto ${CODE_BRIDGE_PORT2}...`);
565093
566048
  server3 = Bun.serve({
565094
- port: CODE_BRIDGE_PORT,
566049
+ port: CODE_BRIDGE_PORT2,
565095
566050
  fetch(req, server4) {
565096
566051
  const url3 = new URL(req.url);
565097
566052
  if (url3.pathname === "/ws") {
565098
566053
  const id = crypto.randomUUID();
565099
- const upgraded = server4.upgrade(req, { data: { id } });
566054
+ const upgraded = server4.upgrade(req, { data: { id, lastPong: Date.now() } });
565100
566055
  if (upgraded)
565101
566056
  return;
566057
+ console.log(`[Code Bridge] \u274C WebSocket upgrade failed for ${req.url}`);
565102
566058
  return new Response("WebSocket upgrade failed", { status: 400 });
565103
566059
  }
565104
566060
  if (url3.pathname === "/health") {
565105
- return new Response(JSON.stringify({ ok: true, port: CODE_BRIDGE_PORT }), {
566061
+ return new Response(JSON.stringify({ ok: true, port: CODE_BRIDGE_PORT2 }), {
565106
566062
  headers: { "Content-Type": "application/json" }
565107
566063
  });
565108
566064
  }
@@ -565111,12 +566067,45 @@ var init_src4 = __esm(() => {
565111
566067
  headers: { "Content-Type": "application/json" }
565112
566068
  });
565113
566069
  }
566070
+ if (url3.pathname.startsWith("/status/")) {
566071
+ const taskId = url3.pathname.split("/")[2];
566072
+ console.log(`[Code Bridge] \uD83D\uDCCA Status request for task: ${taskId}`);
566073
+ return new Response(JSON.stringify(manager4.statusForTask(taskId)), {
566074
+ headers: { "Content-Type": "application/json" }
566075
+ });
566076
+ }
566077
+ if (url3.pathname.startsWith("/cancel/")) {
566078
+ const taskId = url3.pathname.split("/")[2];
566079
+ console.log(`[Code Bridge] \uD83D\uDED1 Cancel request for task: ${taskId}`);
566080
+ const ok = manager4.cancel(taskId);
566081
+ return new Response(JSON.stringify({ ok, taskId }), {
566082
+ headers: { "Content-Type": "application/json" }
566083
+ });
566084
+ }
565114
566085
  return new Response("Not found", { status: 404 });
565115
566086
  },
565116
566087
  websocket: {
565117
566088
  open(ws) {
566089
+ console.log(`[Code Bridge] \u2705 WebSocket client connected`);
565118
566090
  manager4.subscribe(ws);
565119
566091
  ws.send(JSON.stringify(manager4.status()));
566092
+ ws.data.lastPong = Date.now();
566093
+ const heartbeatInterval = setInterval(() => {
566094
+ if (ws.readyState === WebSocket.OPEN) {
566095
+ const timeSinceLastPong = Date.now() - ws.data.lastPong;
566096
+ if (timeSinceLastPong > HEARTBEAT_TIMEOUT) {
566097
+ console.log(`[Code Bridge] \u26A0\uFE0F Client no respondi\xF3 heartbeat en ${timeSinceLastPong}ms, cerrando conexi\xF3n`);
566098
+ clearInterval(heartbeatInterval);
566099
+ ws.close();
566100
+ return;
566101
+ }
566102
+ console.log(`[Code Bridge] \uD83D\uDC93 Enviando heartbeat...`);
566103
+ ws.send(JSON.stringify({ type: "ping" }));
566104
+ } else {
566105
+ clearInterval(heartbeatInterval);
566106
+ }
566107
+ }, HEARTBEAT_INTERVAL);
566108
+ ws._heartbeatInterval = heartbeatInterval;
565120
566109
  },
565121
566110
  async message(ws, raw) {
565122
566111
  let parsed;
@@ -565128,41 +566117,79 @@ var init_src4 = __esm(() => {
565128
566117
  }
565129
566118
  const cmd = DashboardCommand.safeParse(parsed);
565130
566119
  if (!cmd.success) {
566120
+ console.log(`[Code Bridge] \u26A0\uFE0F Invalid command: ${cmd.error.message}`);
565131
566121
  ws.send(JSON.stringify({ type: "error", message: cmd.error.message }));
565132
566122
  return;
565133
566123
  }
565134
566124
  const command2 = cmd.data;
566125
+ console.log(`[Code Bridge] \uD83D\uDCE9 Received command: ${command2.cmd}`, command2.taskId ? `for task ${command2.taskId}` : "");
565135
566126
  switch (command2.cmd) {
565136
566127
  case "launch": {
565137
566128
  try {
566129
+ console.log(`[Code Bridge] \uD83D\uDE80 Launching ${command2.config.cli} for task ${command2.taskId}...`);
565138
566130
  const pid = await manager4.launch(command2.taskId, command2.config, command2.prompt);
566131
+ console.log(`[Code Bridge] \u2705 Launched ${command2.config.cli} with PID ${pid}`);
565139
566132
  ws.send(JSON.stringify({ type: "ack", cmd: "launch", taskId: command2.taskId, pid }));
565140
566133
  } catch (err) {
566134
+ console.log(`[Code Bridge] \u274C Launch error: ${err.message}`);
565141
566135
  ws.send(JSON.stringify({ type: "error", message: err.message }));
565142
566136
  }
565143
566137
  break;
565144
566138
  }
565145
566139
  case "cancel": {
566140
+ console.log(`[Code Bridge] \uD83D\uDED1 Cancelling task ${command2.taskId}...`);
565146
566141
  const ok = manager4.cancel(command2.taskId);
566142
+ console.log(`[Code Bridge] ${ok ? "\u2705" : "\u274C"} Cancel ${ok ? "success" : "failed"}`);
565147
566143
  ws.send(JSON.stringify({ type: "ack", cmd: "cancel", taskId: command2.taskId, ok }));
565148
566144
  break;
565149
566145
  }
565150
566146
  case "status": {
566147
+ console.log(`[Code Bridge] \uD83D\uDCCA Status request`);
565151
566148
  ws.send(JSON.stringify(manager4.status()));
565152
566149
  break;
565153
566150
  }
565154
566151
  case "ping": {
566152
+ ws.data.lastPong = Date.now();
566153
+ console.log(`[Code Bridge] \u2705 Heartbeat recibido del cliente`);
565155
566154
  ws.send(JSON.stringify({ type: "pong" }));
565156
566155
  break;
565157
566156
  }
566157
+ case "feedback": {
566158
+ console.log(`[Code Bridge] \uD83D\uDCAC Feedback recibido para task ${command2.taskId}: ${command2.feedback?.substring(0, 100)}...`);
566159
+ const status = manager4.statusForTask(command2.taskId);
566160
+ if (status.found && status.state === "running") {
566161
+ console.log(`[Code Bridge] \uD83D\uDCE4 Forwarding feedback to agent...`);
566162
+ ws.send(JSON.stringify({
566163
+ type: "feedback:ack",
566164
+ taskId: command2.taskId,
566165
+ delivered: true
566166
+ }));
566167
+ } else {
566168
+ ws.send(JSON.stringify({
566169
+ type: "feedback:ack",
566170
+ taskId: command2.taskId,
566171
+ delivered: false,
566172
+ reason: status.found ? "Agent not running" : "Task not found"
566173
+ }));
566174
+ }
566175
+ break;
566176
+ }
565158
566177
  }
565159
566178
  },
565160
566179
  close(ws) {
566180
+ console.log(`[Code Bridge] \uD83D\uDD0C WebSocket client disconnected`);
565161
566181
  manager4.unsubscribe(ws);
566182
+ if (ws._heartbeatInterval) {
566183
+ clearInterval(ws._heartbeatInterval);
566184
+ ws._heartbeatInterval = null;
566185
+ }
565162
566186
  }
565163
566187
  }
565164
566188
  });
565165
- console.log(`\uD83C\uDF09 Hive Code Bridge running on ws://localhost:${server3.port}`);
566189
+ console.log(`\uD83C\uDF09 [Code Bridge] Servidor corriendo en ws://localhost:${server3.port}`);
566190
+ console.log(`\uD83C\uDF09 [Code Bridge] Health: http://localhost:${server3.port}/health`);
566191
+ console.log(`\uD83C\uDF09 [Code Bridge] WebSocket: ws://localhost:${server3.port}/ws`);
566192
+ console.log(`\uD83C\uDF09 [Code Bridge] Heartbeat: cada ${HEARTBEAT_INTERVAL / 1000}s, timeout: ${HEARTBEAT_TIMEOUT / 1000}s`);
565166
566193
  });
565167
566194
 
565168
566195
  // packages/cli/src/commands/gateway.ts
@@ -565325,7 +566352,7 @@ async function start(flags) {
565325
566352
  \u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2551
565326
566353
  \u2551 \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u2551
565327
566354
  \u2551 \u2551
565328
- \u2551 Personal Swarm AI Gateway \u2014 v0.0.8 \u2551
566355
+ \u2551 Personal Swarm AI Gateway \u2014 v0.0.11 \u2551
565329
566356
  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
565330
566357
 
565331
566358
  \uD83D\uDCE6 Installation: ${adapter.name}
@@ -565393,10 +566420,37 @@ async function handleDevMode(adapter, gatewayConfig, daemon) {
565393
566420
  viteProcess.unref();
565394
566421
  }
565395
566422
  }
566423
+ console.log("[Gateway] \uD83C\uDF09 Iniciando Code Bridge...");
565396
566424
  try {
565397
566425
  await Promise.resolve().then(() => (init_src4(), exports_src));
566426
+ console.log("\uD83C\uDF09 Code Bridge iniciado en puerto 18791");
566427
+ const CODE_BRIDGE_PORT3 = 18791;
566428
+ let codeBridgeReady = false;
566429
+ console.log(`[Gateway] \uD83C\uDF09 Esperando Code Bridge en puerto ${CODE_BRIDGE_PORT3}...`);
566430
+ for (let i2 = 0;i2 < 50; i2++) {
566431
+ try {
566432
+ const response = await fetch(`http://localhost:${CODE_BRIDGE_PORT3}/health`, {
566433
+ signal: AbortSignal.timeout(200)
566434
+ });
566435
+ if (response.ok) {
566436
+ codeBridgeReady = true;
566437
+ console.log(`[Gateway] \uD83C\uDF09 \u2705 Code Bridge disponible despu\xE9s de ${(i2 + 1) * 100}ms`);
566438
+ break;
566439
+ }
566440
+ } catch (fetchError) {
566441
+ if (i2 % 10 === 0) {
566442
+ console.log(`[Gateway] \uD83C\uDF09 \u23F3 Esperando Code Bridge... intento ${i2 + 1}/50`);
566443
+ }
566444
+ await new Promise((resolve9) => setTimeout(resolve9, 100));
566445
+ }
566446
+ }
566447
+ if (!codeBridgeReady) {
566448
+ console.warn("[Gateway] \uD83C\uDF09 \u26A0\uFE0F Code Bridge no respondi\xF3 a tiempo - las herramientas codebridge pueden fallar");
566449
+ } else {
566450
+ console.log("[Gateway] \uD83C\uDF09 \u2705 Code Bridge listo para aceptar conexiones");
566451
+ }
565398
566452
  } catch (error50) {
565399
- console.warn(`\u26A0\uFE0F No se pudo iniciar el Code Bridge: ${error50.message}`);
566453
+ console.warn(`[Gateway] \uD83C\uDF09 \u274C No se pudo iniciar el Code Bridge: ${error50.message}`);
565400
566454
  }
565401
566455
  const spawnGateway = () => {
565402
566456
  const gw = spawn8(process.execPath, [process.argv[1] || "", "start", "--skip-check", "--dev-internal"], {
@@ -565443,7 +566497,7 @@ async function handleDevMode(adapter, gatewayConfig, daemon) {
565443
566497
  console.log("\u23F3 Esperando servicios...");
565444
566498
  const [viteReady, gatewayReady] = await Promise.all([
565445
566499
  hasVite ? waitForVite(5173, 30000) : Promise.resolve(true),
565446
- waitForPort2(18790, 30000)
566500
+ waitForHttpPort(18790, "/health", 30000)
565447
566501
  ]);
565448
566502
  if (!viteReady && hasVite) {
565449
566503
  console.error("\u26A0\uFE0F Vite no respondi\xF3 a tiempo");
@@ -565452,10 +566506,11 @@ async function handleDevMode(adapter, gatewayConfig, daemon) {
565452
566506
  console.error("\u26A0\uFE0F Gateway no respondi\xF3 a tiempo");
565453
566507
  return;
565454
566508
  }
566509
+ await Bun.sleep(500);
565455
566510
  console.log(`\u2705 Servicios listos
565456
566511
  `);
565457
566512
  const setupMode = await isSetupMode2();
565458
- const browserPort = hasVite ? 5173 : 18790;
566513
+ const browserPort = gatewayConfig.port;
565459
566514
  const url3 = setupMode ? `http://localhost:${browserPort}/setup` : `http://localhost:${browserPort}`;
565460
566515
  console.log(`
565461
566516
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
@@ -565465,6 +566520,7 @@ async function handleDevMode(adapter, gatewayConfig, daemon) {
565465
566520
  \u2551 API: http://127.0.0.1:18790 \u2551
565466
566521
  \u2551 WebSocket: ws://127.0.0.1:18790/ws \u2551
565467
566522
  \u2551 Canvas: ws://127.0.0.1:18790/canvas\u2551
566523
+ \u2551 Vite HMR: http://localhost:5173 \u2551
565468
566524
  \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
565469
566525
  \u2551 ${setupMode ? "\uD83C\uDF89 Primer arranque \u2014 abriendo setup..." : "Administra tu Hive aqu\xED "}\u2551
565470
566526
  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
@@ -565480,11 +566536,37 @@ async function handleProductionMode(adapter, gatewayConfig, daemon) {
565480
566536
  await startGateway(coreConfig);
565481
566537
  return;
565482
566538
  }
566539
+ console.log("[Gateway] \uD83C\uDF09 Iniciando Code Bridge...");
565483
566540
  try {
565484
566541
  await Promise.resolve().then(() => (init_src4(), exports_src));
565485
566542
  console.log("\uD83C\uDF09 Code Bridge iniciado en puerto 18791");
566543
+ const CODE_BRIDGE_PORT3 = 18791;
566544
+ let codeBridgeReady = false;
566545
+ console.log(`[Gateway] \uD83C\uDF09 Esperando Code Bridge en puerto ${CODE_BRIDGE_PORT3}...`);
566546
+ for (let i2 = 0;i2 < 50; i2++) {
566547
+ try {
566548
+ const response = await fetch(`http://localhost:${CODE_BRIDGE_PORT3}/health`, {
566549
+ signal: AbortSignal.timeout(200)
566550
+ });
566551
+ if (response.ok) {
566552
+ codeBridgeReady = true;
566553
+ console.log(`[Gateway] \uD83C\uDF09 \u2705 Code Bridge disponible despu\xE9s de ${(i2 + 1) * 100}ms`);
566554
+ break;
566555
+ }
566556
+ } catch (fetchError) {
566557
+ if (i2 % 10 === 0) {
566558
+ console.log(`[Gateway] \uD83C\uDF09 \u23F3 Esperando Code Bridge... intento ${i2 + 1}/50`);
566559
+ }
566560
+ await new Promise((resolve9) => setTimeout(resolve9, 100));
566561
+ }
566562
+ }
566563
+ if (!codeBridgeReady) {
566564
+ console.warn("[Gateway] \uD83C\uDF09 \u26A0\uFE0F Code Bridge no respondi\xF3 a tiempo - las herramientas codebridge pueden fallar");
566565
+ } else {
566566
+ console.log("[Gateway] \uD83C\uDF09 \u2705 Code Bridge listo para aceptar conexiones");
566567
+ }
565486
566568
  } catch (error50) {
565487
- console.warn(`\u26A0\uFE0F No se pudo iniciar el Code Bridge: ${error50.message}`);
566569
+ console.warn(`[Gateway] \uD83C\uDF09 \u274C No se pudo iniciar el Code Bridge: ${error50.message}`);
565488
566570
  }
565489
566571
  const adapterConfig = await adapter.getConfig();
565490
566572
  const isDocker = adapterConfig.type === "docker" || adapterConfig.type === "binary" && process.env.HIVE_UI_DIR === "/app/ui";
@@ -567688,7 +568770,7 @@ async function executeAsync(gatewayUrl, payload, spinner) {
567688
568770
  }
567689
568771
 
567690
568772
  // packages/cli/src/index.ts
567691
- var VERSION4 = "0.0.8";
568773
+ var VERSION4 = "0.0.11";
567692
568774
  var HELP = `
567693
568775
  \uD83D\uDC1D Hive \u2014 Personal Swarm AI Gateway v${VERSION4}
567694
568776