Core API Reference¶
core.database ¶
Functions¶
dispose_engine
async
¶
Cierra el pool de conexiones limpiamente — llamar antes de shutdown.
Source code in core/database.py
create_schema
async
¶
Crea un esquema PostgreSQL si no existe (async).
Source code in core/database.py
create_tables_in_schema
async
¶
Crea las tablas SQLModel en el esquema indicado usando el motor async.
Source code in core/database.py
list_schemas
async
¶
Lista los esquemas (workspaces) disponibles.
Source code in core/database.py
drop_schema
async
¶
Elimina un esquema y todos sus objetos (CASCADE).
Source code in core/database.py
startup_db
async
¶
Inicializa el motor y crea tablas en el esquema main.
Alembic se invoca manualmente: poetry run alembic upgrade head
Source code in core/database.py
core.config ¶
Configuración global de Morphix — Settings con pydantic-settings.
Classes¶
Settings ¶
Bases: BaseSettings
Configuración global de Morphix
Source code in core/config.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
Functions¶
ensure_encryption_key ¶
Valida que encryption_key exista. En producción lanza error, en desarrollo auto-genera.
Source code in core/config.py
core.path_resolver ¶
PathResolver — resolución centralizada de rutas del sistema. Elimina hardcodeos de Path("memory"), Path("workspaces"), Path("graficos"), etc.
Classes¶
PathResolver ¶
Provee rutas canónicas para todos los subsistemas.
Source code in core/path_resolver.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | |
Functions¶
normalize_path
staticmethod
¶
Normaliza una ruta relativa eliminando el prefijo project_root si está presente.
Casos
file_path='code_projects/miapp/src/main.py', project_root='code_projects/miapp' → 'src/main.py' file_path='miapp/src/main.py', project_root='code_projects/miapp' → 'src/main.py' (el último componente 'miapp' se elimina) file_path='src/main.py', project_root='code_projects/miapp' → 'src/main.py' (sin cambios)
Fuente única de verdad para normalización de rutas en todo el sistema.
Source code in core/path_resolver.py
normalize_project_root
staticmethod
¶
Asegura que project_root tenga el prefijo 'code_projects/'.
Source code in core/path_resolver.py
core.health ¶
Health check — runtime connectivity probes.
Usage: poetry run python -m core.health
Classes¶
HealthReport
dataclass
¶
Structured health check result for all services.
Source code in core/health.py
Functions¶
check_database
async
¶
Probe PostgreSQL connectivity with async SELECT 1.
Source code in core/health.py
check_llm
async
¶
Probe LLM provider reachability with a fast connectivity check.
Source code in core/health.py
check_redis
async
¶
Probe Redis connectivity if configured.
Source code in core/health.py
check_filesystem ¶
Probe critical directories and workspace integrity.
Source code in core/health.py
check_workspace ¶
Probe current workspace integrity.
Source code in core/health.py
run_health_check
async
¶
Run all health checks and return a structured report.
Source code in core/health.py
core.bootstrap ¶
Bootstrap — inicialización del backend para el modo desktop PySide6.
Functions¶
validate_config ¶
Validate critical configuration at startup.
Returns (valid: bool, warnings: list[str]). Fatal errors raise ValueError. Warnings are non-blocking.
Source code in core/bootstrap.py
init_backend
async
¶
init_backend(
workspace: str | None = None,
on_progress: Callable[[str], None] | None = None,
) -> bool
Inicializa BD, workspace, y agentes.
Source code in core/bootstrap.py
start_daemons
async
¶
Arranca tareas de fondo: Kairos Daemon y OfflineManager. on_offline_changed: callback opcional async para notificar cambios de estado offline.
Source code in core/bootstrap.py
stop_daemons
async
¶
Cancela todas las tareas de fondo limpiamente.
Source code in core/bootstrap.py
core.feature_flags ¶
Kairos Feature Flags + Daemon Mode (Claude Code Style - Marzo 2026)
Classes¶
KairosFlags ¶
Source code in core/feature_flags.py
Functions¶
get ¶
Obtener flag. Solo recarga del .env si no fue modificado en caliente.
Source code in core/feature_flags.py
set ¶
Cambiar flag en runtime (marcado como manual para evitar hot-reload).
daemon_loop
async
¶
Modo Daemon siempre activo
Source code in core/feature_flags.py
core.circuit_breaker ¶
Circuit Breaker — protege contra fallos en cascada en llamadas externas.
Implementa el patrón Circuit Breaker para proveedores LLM: - CLOSED: operación normal, se envían requests - OPEN: demasiados fallos consecutivos, se rechazan requests inmediatamente - HALF_OPEN: timeout de recuperación expirado, se permite un request de prueba
Classes¶
CircuitBreaker
dataclass
¶
Circuit breaker para un proveedor externo.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
failure_threshold |
int
|
fallos consecutivos para abrir el circuito |
5
|
recovery_timeout |
float
|
segundos antes de intentar half-open |
30.0
|
Source code in core/circuit_breaker.py
Functions¶
allow_request ¶
True si el request debe enviarse, False si debe rechazarse (circuito abierto).
Source code in core/circuit_breaker.py
record_success ¶
record_failure ¶
Registra un fallo. Si se supera el umbral, abre el circuito.
Source code in core/circuit_breaker.py
CircuitBreakerRegistry ¶
Registro global de circuit breakers por proveedor.
Source code in core/circuit_breaker.py
core.rate_limiter ¶
Rate Limiter — control de consumo de llamadas LLM.
Sliding window: limita el número de llamadas por minuto y por hora. Configurable desde Kairos feature flags.
Classes¶
RateLimiter ¶
Rate limiter con sliding window para llamadas LLM.
Source code in core/rate_limiter.py
Functions¶
acquire
async
¶
Intenta adquirir un slot. Retorna True si está permitido, False si debe esperar.
Source code in core/rate_limiter.py
wait_and_acquire
async
¶
Espera hasta que haya un slot disponible o se alcance el timeout.
Source code in core/rate_limiter.py
remaining
async
¶
Número de slots disponibles en la ventana actual.
Source code in core/rate_limiter.py
core.token_counter ¶
Token Counter — carga lazy de tiktoken.
Centraliza la codificación cl100k_base para evitar cargarla en 4 lugares distintos.
Functions¶
get_encoding ¶
Return the tiktoken cl100k_base encoding with lazy loading.
La primera llamada carga el encoding (~1-2 MB, ~100ms). Llamadas subsecuentes retornan la instancia cacheada.
Source code in core/token_counter.py
core.cache_manager ¶
Prompt Cache Manager — multi-provider cache abstraction.
DeepSeek (now): Automatic server-side disk caching. No client API needed. We monitor cache hit/miss via response.usage fields.
Anthropic (future): Client-controlled ephemeral caching via cache_control markers. We inject {"type": "ephemeral"} on system/tools messages.
OpenAI (future): Automatic prompt caching (newer models). Monitor like DeepSeek.
Design
- CacheManager is a singleton that accumulates per-workspace cache stats.
- track_usage() extracts prompt_cache_hit_tokens / prompt_cache_miss_tokens from any provider response.
- get_stats() returns hit rate and token savings for reporting.
- stabilize_messages() is a helper that keeps the message prefix intact (critical for DeepSeek's prefix-based disk caching).
Classes¶
CacheManager ¶
Source code in core/cache_manager.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
Functions¶
track_usage ¶
track_usage(
prompt_tokens: int = 0,
completion_tokens: int = 0,
prompt_cache_hit_tokens: int = 0,
prompt_cache_miss_tokens: int = 0,
workspace: str = "main",
) -> None
Record token usage and cache metrics from an LLM response.
Source code in core/cache_manager.py
get_stats ¶
Return cache statistics as a dict for reporting.
Source code in core/cache_manager.py
stabilize_messages
staticmethod
¶
Compress messages while preserving the prefix for optimal caching.
Unlike compress_history() which removes middle messages (breaking the prefix for DeepSeek's disk cache), this method keeps the beginning intact and summarizes the middle into a single injected context message.
Strategy for DeepSeek::
``[system] [user1] [assistant1] [user2] [assistant2] ... [userN]``
``└────── PREFIX (cacheable) ──────┘└── middle ──┘└ recent ─┘``
We keep: system + first 2 turns (prefix) + last 4 turns (recent) We summarize middle turns into a single system-injected context note.
Source code in core/cache_manager.py
core.context_manager ¶
Context Manager — gestión inteligente de ventana de contexto para LLMs.
Classes¶
ContextManager ¶
Gestión de ventana de contexto: estimación de tokens, compresión, chunking.
Source code in core/context_manager.py
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
Functions¶
estimate_tokens
classmethod
¶
Estima el número de tokens en una lista de mensajes.
Source code in core/context_manager.py
compress_history
classmethod
¶
Comprime el historial manteniendo system prompt y últimos mensajes.
Source code in core/context_manager.py
chunk_large_file
classmethod
¶
Divide archivos grandes en chunks solapados con metadatos.
Source code in core/context_manager.py
summarize_for_context
classmethod
¶
Resume un texto para incluirlo en contexto limitado.
build_context_summary
classmethod
¶
Construye un resumen del historial para inyectar en nuevo contexto.
Source code in core/context_manager.py
core.change_tracker ¶
Change Tracker — undo/redo de cambios de archivos.
Antes de cada file_manager.write, guarda una copia de respaldo. El usuario puede revertir cambios con el comando 'undo'.
Classes¶
ChangeTracker ¶
Registra cambios de archivos para permitir undo.
Source code in core/change_tracker.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
Functions¶
save_before_write ¶
Guarda el contenido actual antes de sobrescribir. Retorna el key de undo.
Source code in core/change_tracker.py
undo_last ¶
Undo the last change. Returns the restored file path.
Source code in core/change_tracker.py
redo_last ¶
Re-apply the last undone change.
Source code in core/change_tracker.py
list_undo_stack ¶
Lista los backups disponibles para undo.
Source code in core/change_tracker.py
core.codebase_indexer ¶
Codebase Indexer — indexación semántica con FAISS + cache en disco.
Classes¶
CodebaseIndexer ¶
Indexa un codebase con FAISS para búsqueda semántica de código relevante.
Source code in core/codebase_indexer.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
Functions¶
index_project ¶
index_project(
patterns: list[str] | None = None,
max_files: int = MAX_FILES,
force: bool = False,
progress_callback: Callable[[dict], None] | None = None,
) -> int
Indexa archivos incrementalmente (solo archivos modificados desde último index).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patterns |
list[str] | None
|
Extensiones a indexar (None = CODE_EXTENSIONS). |
None
|
max_files |
int
|
Máximo de archivos a indexar. |
MAX_FILES
|
force |
bool
|
Si True, reindexa todo ignorando cache. |
False
|
progress_callback |
Callable[[dict], None] | None
|
Callable(dict) para reportar progreso. |
None
|
Returns:
| Type | Description |
|---|---|
int
|
Número de chunks indexados en esta ejecución. |
Source code in core/codebase_indexer.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | |
core.embedding_provider ¶
Classes¶
EmbeddingProvider ¶
Provider lazy de embeddings — carga en background sin bloquear arranque.
Source code in core/embedding_provider.py
Functions¶
get_instance
classmethod
¶
Retorna el modelo si está listo. Si no, inicia carga en background. Retorna None hasta que el modelo esté completamente cargado.
Source code in core/embedding_provider.py
encode
classmethod
¶
Wrapper con fallback: si el modelo no está listo, retorna None.
wait_until_ready
classmethod
¶
Espera hasta que el modelo esté cargado. Retorna True si listo.
core.faiss_indexer ¶
FAISS Indexer — indexación semántica reutilizable con FAISS + SentenceTransformer.
Classes¶
FAISSIndexer ¶
Indexación FAISS reutilizable: add, search, save, load, rebuild.
Source code in core/faiss_indexer.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
Functions¶
add ¶
Añade un documento al índice.
Source code in core/faiss_indexer.py
search ¶
Búsqueda semántica. Retorna [{key, value, distance, similarity}].
Source code in core/faiss_indexer.py
remove ¶
rebuild_index ¶
Reconstruye el índice desde cero basado en documents.
Source code in core/faiss_indexer.py
clear ¶
save ¶
Persiste el índice FAISS y documentos a disco.
Source code in core/faiss_indexer.py
load
classmethod
¶
Carga un índice FAISS desde disco.
Source code in core/faiss_indexer.py
core.git_operations ¶
Git Operations — helper centralizado para auto-commit y operaciones git comunes.
Smart commit: generates the commit message via LLM based on the task.
Functions¶
auto_commit
async
¶
auto_commit(
workspace: str,
project_root: str | None = None,
message: str = "Auto-commit: tarea completada",
) -> dict
Ejecuta git init, add -A, commit automático. Retorna {success, output}.
Source code in core/git_operations.py
smart_auto_commit
async
¶
smart_auto_commit(
workspace: str,
project_root: str | None = None,
task_description: str = "",
files_written: list[str] | None = None,
) -> dict
Commit automático con mensaje generado por LLM basado en la tarea.
Si task_description está vacío, usa el mensaje por defecto. Si hay LLM disponible, genera un resumen de una línea de los cambios.
Source code in core/git_operations.py
core.hooks_registry ¶
Classes¶
HookContext
dataclass
¶
Immutable context passed to every hook invocation.
Source code in core/hooks_registry.py
HooksRegistry ¶
Registry for hook callables organized by hook point name.
Mirrors ToolsRegistry pattern: decorator-based registration, global + workspace-scoped via load/unload lifecycle.
Source code in core/hooks_registry.py
Functions¶
register ¶
Decorator: @hooks_registry.register('on_before_tool')
Source code in core/hooks_registry.py
dispatch
async
¶
Invoke all hooks registered for hook_point. Exceptions are caught and logged.
Source code in core/hooks_registry.py
unregister ¶
Remove a single hook from a hook point.
Source code in core/hooks_registry.py
clear_hook_point ¶
clear ¶
Remove all hooks (used on workspace switch to clean workspace hooks).
list_hooks ¶
Return {hook_point: [function_names]} for introspection.
core.hook_loader ¶
Functions¶
load_global_hooks ¶
Load global hooks from core/hooks/.
Source code in core/hook_loader.py
load_workspace_hooks ¶
Load workspace-local hooks from workspaces/
Source code in core/hook_loader.py
unload_workspace_hooks ¶
Remove only workspace-scoped hooks from registry and sys.modules.
Source code in core/hook_loader.py
core.lru_cache ¶
LRU Cache — thread-safe, TTL, tamaño limitado.
Usado por TaskAnalyzer y AgentRouter para cachear resultados de LLM.
Classes¶
LRUCache ¶
Source code in core/lru_cache.py
Functions¶
get ¶
Retorna valor cacheado si existe y no expiró. None si no.
Source code in core/lru_cache.py
set ¶
Guarda valor en cache con timestamp actual.
Source code in core/lru_cache.py
clear_expired ¶
Elimina entradas expiradas. Retorna cuántas eliminó.
Source code in core/lru_cache.py
core.metrics ¶
Metrics — contadores de uso del sistema.
Métricas acumulativas: tokens, workflows, herramientas. Métricas por herramienta: éxito/fallo, latencia. Expuestas via comando :stats en CLI y panel desktop.
Classes¶
Metrics
dataclass
¶
Source code in core/metrics.py
Functions¶
record_llm_usage ¶
record_llm_usage(
prompt_tokens: int = 0,
completion_tokens: int = 0,
cache_hit_tokens: int = 0,
cache_miss_tokens: int = 0,
) -> None
Record per-call token usage including cache hit/miss from DeepSeek.
Source code in core/metrics.py
ToolMetrics
dataclass
¶
Métricas por herramienta: éxito/fallo y latencia.
Source code in core/metrics.py
Functions¶
record_call ¶
Registra una llamada a herramienta con su resultado y latencia.
Source code in core/metrics.py
get_tool_stats ¶
Devuelve las métricas de una herramienta o None.
get_all_stats ¶
get_summary ¶
Resumen agregado de todas las herramientas.
Source code in core/metrics.py
core.models ¶
core.utils ¶
Utilidades generales de Morphix
Functions¶
clean_llm_response ¶
Limpieza ULTRA-agresiva de respuestas del LLM. Versión canónica — fusiona la detección de coroutine (memory/manager.py) y el regex eval_count (workflow_utils.py).
Source code in core/utils.py
core.workspaces ¶
Classes¶
Workspaces ¶
Source code in core/workspaces.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | |
Functions¶
core.workflow_state ¶
core.memory.manager ¶
MemoryManager - Sistema de 3 Capas Self-Healing (VERSIÓN FINAL ROBUSTA Y ESTABLE) Aislamiento por workspace: subdirectorios memory/{workspace}/
Classes¶
MemoryManager ¶
Source code in core/memory/manager.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 | |
Functions¶
switch_workspace
async
¶
Switch to the given workspace, loading its documents and index. Embedding computation runs in a thread pool to avoid blocking the event loop.
Source code in core/memory/manager.py
write_system
async
¶
Escribe en memory/system/ sin interferir con el índice activo.
Source code in core/memory/manager.py
search ¶
Búsqueda semántica real usando FAISS. Retorna top-k documentos con scores.
Source code in core/memory/manager.py
Functions¶
core.mcp.server ¶
MCP server — expose Morphix tools over stdio JSON-RPC.
Usage
morphix mcp-server poetry run python -m core.mcp.server
Other MCP clients (opencode, Claude Desktop) can connect and use Morphix tools: file_manager, bash_manager, web_search, etc.
Classes¶
MCPServer ¶
Source code in core/mcp/server.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | |
Functions¶
run
async
¶
Main loop: read JSON-RPC from stdin, respond on stdout.
Source code in core/mcp/server.py
Functions¶
run_mcp_server ¶
Entry point for 'morphix mcp-server'.
Source code in core/mcp/server.py
core.mcp.client ¶
MCP client — connect to external MCP servers, discover and proxy their tools.
Classes¶
MCPClient ¶
Manages one MCP server connection (subprocess via stdio).
Source code in core/mcp/client.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
Functions¶
connect
async
¶
Spawn the MCP server subprocess and perform initialization handshake.
Source code in core/mcp/client.py
call_tool
async
¶
Call a tool on the MCP server. Returns Morphix-format result dict.
Source code in core/mcp/client.py
disconnect
async
¶
Terminate the MCP server subprocess.
Source code in core/mcp/client.py
Functions¶
connect_mcp_servers
async
¶
Connect to all MCP servers configured for a workspace.
Source code in core/mcp/client.py
disconnect_mcp_servers
async
¶
get_mcp_client_for_tool ¶
Find the MCP client that owns a given tool name (mcp:
Source code in core/mcp/client.py
core.mcp.config ¶
Load MCP server configurations from JSON files.
Functions¶
load_mcp_servers ¶
Load MCP server configs. Workspace-local overrides global.
Source code in core/mcp/config.py
core.mcp.adapter ¶
Convert between Morphix ToolDefinition and MCP tool schema.
MCP tool format
{"name": "...", "description": "...", "inputSchema": {"type": "object", "properties": {...}, "required": [...]}}
Morphix tools use OpenAI function-calling format — we convert at the bridge.
Functions¶
morphix_to_mcp_tool ¶
Convert a Morphix tool dict to MCP tool format.
Input: {"name": "...", "description": "...", "parameters": {...}, "required": [...]} Output: {"name": "...", "description": "...", "inputSchema": {"type": "object", "properties": {...}, "required": [...]}}
Source code in core/mcp/adapter.py
mcp_tool_to_morphix_params ¶
Extract Morphix-compatible params from an MCP tool schema.
Returns a dict suitable for tools_registry + tool_specs registration.
Source code in core/mcp/adapter.py
mcp_result_to_morphix ¶
Convert MCP tools/call result to Morphix tool output format.
MCP content: [{"type": "text", "text": "..."}, {"type": "image", "data": "...", "mimeType": "..."}] Morphix expects: {"success": bool, "output": str, ...}
Source code in core/mcp/adapter.py
core.mcp.protocol ¶
JSON-RPC 2.0 framing over asyncio streams.
MCP uses JSON-RPC 2.0 with newline-delimited JSON over stdio. Messages are one JSON object per line (no pretty-print, no embedded newlines).
Functions¶
read_message
async
¶
Read one newline-delimited JSON message from a stream.
Source code in core/mcp/protocol.py
write_message
async
¶
Write one JSON message as a single line to a stream.
Source code in core/mcp/protocol.py
core.security.anti_distillation ¶
Anti-distillation hardening — watermark rotation, pattern detection, escalation.
Companion to undercover_mode.py. Provides: 1. Watermark rotation — 8 styles, rotated per workspace+time seed 2. Query similarity tracking — detects N similar queries (extraction pattern) 3. Escalation levels — warn → throttle → honeypot → lock 4. Honeypot generator — fake system prompts to waste attackers
Classes¶
WatermarkRotator ¶
Rotates watermark styles per workspace + time window.
Source code in core/security/anti_distillation.py
Functions¶
get_watermark ¶
Return rotated watermark for given text.
Source code in core/security/anti_distillation.py
DistillationTracker ¶
Tracks query patterns to detect distillation/extraction attempts.
Source code in core/security/anti_distillation.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | |
Functions¶
record_attempt ¶
Record a blocked distillation/jailbreak attempt.
Source code in core/security/anti_distillation.py
check_distillation_pattern ¶
Check if current query is part of a distillation pattern.
Returns True if distillation is detected (multiple similar queries recently).
Source code in core/security/anti_distillation.py
get_escalation_level ¶
Determine escalation based on attempt frequency in last 60 seconds.
Source code in core/security/anti_distillation.py
update_escalation ¶
Update escalation level based on recent attempt frequency.
Source code in core/security/anti_distillation.py
get_throttle_delay ¶
Return artificial delay in seconds based on escalation.
HoneypotInjector ¶
Injects fake internal details into responses when distillation is detected.
Source code in core/security/anti_distillation.py
Functions¶
get_honeypot_snippet
staticmethod
¶
Return a random honeypot snippet.
inject
staticmethod
¶
Inject honeypot content into a response.
Appends fake internal information that looks like leaked system details. The attacker wastes time analyzing fake data.
Source code in core/security/anti_distillation.py
core.security.frustration_detector ¶
Frustration Detector — detects user frustration patterns via regex.
When frustration is detected, the system can adjust agent behavior: switch to calmer mode, slow responses, offer help.
Classes¶
FrustrationDetector ¶
Source code in core/security/frustration_detector.py
Functions¶
check ¶
Check a user query for frustration signals. Returns (is_frustrated, reason).
Source code in core/security/frustration_detector.py
get_calming_prompt ¶
Return a system prompt modifier for frustrated users.
Source code in core/security/frustration_detector.py
core.security.undercover_mode ¶
Undercover Mode + Advanced Anti-Distillation Protection (Versión FINAL - Objetivo 2)
Classes¶
UndercoverMode ¶
Source code in core/security/undercover_mode.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | |
Functions¶
check_query
async
¶
Detección robusta de intentos de distillation / jailbreak
Source code in core/security/undercover_mode.py
add_watermark ¶
Add lightweight rotating watermark for distillation detection.
Source code in core/security/undercover_mode.py
get_safe_response ¶
get_safe_response(
original_response: str,
workspace: str = "main",
skip_watermark: bool = False,
) -> str
Clean and protect the final response. Redacts internal terms and checks for injection.
Source code in core/security/undercover_mode.py
check_response ¶
Scan LLM/tool output for indirect injection patterns. Returns True if response is safe, False if it contains injection attempts.
Source code in core/security/undercover_mode.py
core.sandbox.restricted_executor ¶
RestrictedPython Sandbox — Hardened version - Timeout de ejecución - Guards extremadamente estrictos - Limitación fuerte de imports y builtins - Mejor manejo de errores y mensajes amigables
Classes¶
RestrictedExecutor ¶
Source code in core/sandbox/restricted_executor.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
Functions¶
execute
async
staticmethod
¶
Execute safely with timeout and strict guards.
Source code in core/sandbox/restricted_executor.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
Functions¶
safe_import ¶
Import extremadamente restrictivo
Source code in core/sandbox/restricted_executor.py
core.hooks.audit ¶
Global hook: audit every tool call to the audit log.
Classes¶
Functions¶
audit_on_before_tool ¶
Log tool invocation attempt before execution.
Source code in core/hooks/audit.py
audit_on_after_tool ¶
Log tool result after successful execution.
Source code in core/hooks/audit.py
audit_on_tool_error ¶
Log tool failure with error details.
Source code in core/hooks/audit.py
core.hooks.distillation_guard ¶
Global hook: distillation guard — logs patterns and throttles at escalation level 2+.
Classes¶
Functions¶
distillation_guard_on_before_tool
async
¶
Check distillation escalation before tool execution.
At level 2 (throttle): add artificial delay. At level 4 (lock): reject all tool calls.
Source code in core/hooks/distillation_guard.py
distillation_guard_on_after_tool ¶
Periodic status log at escalation level 1+.
Source code in core/hooks/distillation_guard.py
core.repositories.conversation_repository ¶
Classes¶
ConversationRepository ¶
Repositorio centralizado con todas las operaciones asíncronas.
Source code in core/repositories/conversation_repository.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 | |
Functions¶
save
async
staticmethod
¶
save(
title: str,
user_message: str,
tags: str = "maestro",
workflow_id: int | None = None,
conversation_history: list[dict] | None = None,
conversation_id: int | None = None,
) -> int
Save a new conversation, or append to existing if conversation_id is set.
Returns the conversation id.
Source code in core/repositories/conversation_repository.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
add_messages
async
staticmethod
¶
Append messages to an existing conversation.
Source code in core/repositories/conversation_repository.py
get_messages
async
staticmethod
¶
Obtiene todos los mensajes de una conversación.
Source code in core/repositories/conversation_repository.py
get_conversation
async
staticmethod
¶
Get conversation metadata with message count.
Source code in core/repositories/conversation_repository.py
list_all
async
staticmethod
¶
List conversations with pagination, newest first.
Source code in core/repositories/conversation_repository.py
count_all
async
staticmethod
¶
Total number of conversations in the current workspace schema.