Manual de Usuario de openOnyx (openonyx)
Bienvenido al manual oficial de openonyx, el harness de agente de programación determinista (CLI, TUI y Web PWA embebida) construido sobre el microkernel OnYX (onyx-core → onyx-soul-agents → onyx-workspace → open-onyx).
A diferencia de otros asistentes de terminal que mezclan estado en memoria volátil, openonyx registra cada decisión, lectura, edición y comando en un grafo EAV determinista con:
- Snapshots comprimidos por hitos (
snapshots.onyxpack) con verificación FNV-1a y tolerancia a cortes. - Time-travel y bifurcación segura (
/rewind,/fork,chat --resume --tick,rewind --interactive). - Depurador Temporal Interactivo (
TimeFreeze, SDD-07): pausa la sesión en cualquier tick (TUI:Alt+←/→,Ctrl+T,/time,/go,/step,/step-llm; Web:#tick-pill→ barra ámbar) sobre un anillo RAM de fronteras + hitos en disco; primitivas 0-tokens selladas enONYXTR2(0 red, 0 disco:!cmd,/read,/inject,/step) y cirugía segura del grafo congelado con/graph(inspect/drop-mem/edit-mem/set-goal); 100 % efímero hasta confirmar la bifurcación. - Subagentes asíncronos en worktrees Git aislados (
spawn_subagent//spawn, fusión 3-way con Scent-Heated Merge,--max-subagents, y harnesses CLI externos como drivers opcionales[[external_drivers]]), yspawn_agent(isolated: true): hijos síncronos en worktrees aisladosonyx/sub/agent-*con reconciliación 3-way que nunca tocaHEADni la raíz hasta el merge. - Benchmark multi-modelo (
openonyx bench): mismos snapshot/tick, worktrees desechables por candidato (rewind + RAII), candidatos LLM vivosprovider:modelo replays offlinereplay:<label>=<file.tr>,--verifysandboxed, tabla Markdown de 9 columnas + informe JSON--out; la raíz queda 100 % intacta. - Verify-on-Edit (
[verify]/[[verify.rules]]en.onyx/config.toml): tras cadafs_edit/fs_writeexitoso, ejecuta las reglas cuyaglobempareja el archivo editado (y testsscope:testimpactados por Scent) en sandbox y inyecta[verify: PASS|FAIL|BLOCKED]a la observación del tool, sujeto a Workspace Trust y[permissions].deny. - Objetivo LLM conmutable en caliente (
[[llm_profiles]],/profile//provider//model//effort, cabeceraprovider/modelviva y selector Web sin credenciales) con proveedor nativo Anthropic (Messages API, prompt cachingephemeraly extended thinking acotado con--thinking-budget). - Herramientas dinámicas MCP (
[mcp.servers.<name>]con transportesstdioyhttp): cada tool se expone comomcp__<server>__<tool>, siempre con aprobación explícita,DenyenPLAN/EXPLORE, con gate de Workspace Trust, aislamiento de fallos por servidor y auditoría enopenonyx doctor. - TUI modular
F1..F5(Chat, Agents, Sprout, Plan & Diff, Timeline) con paleta de comandosCtrl+Ky/view. - Checkpoints Git reversibles (
/undo) sin tocarHEADni tu área de staging. - Grabación y reproducción 100% offline (
ONYXTR2, 0 llamadas de red, 0 escrituras en disco). - Seguridad por capas: Workspace Trust con
blake3(openonyx trust//trust), modosPLAN/BUILD/EXPLORE, reglas.onyx/config.toml(deny > ask > allow), Scent-Heated Approvals, sandbox OS conenv_clear(), protección RO del Control Plane yProcessJobRAII. - Interfaz Web / PWA embebida (
openonyx serve): servidor HTTP/1.1 + SSE puro enstd::net(0tokio), pensado para navegador local, móvil Android/iOS o despliegue detrás de proxy HTTPS, con autenticación constante porblake3(CookieHttpOnly/Bearer) y--cors-originpara clientes externos. - Navegación semántica AST Scent 2.0 (
onyx-scent:scent_outline+scent_impact+scent_references): 7 lenguajes (Rust, Python, Java, TypeScript, JavaScript, Go, C/C++), tiposEntityKind::{TypeAlias, Component}, caché binaria incremental.onyx/scent.idx(ONYXSCI1, recarga < 20 ms) y CLIscent outline|impact|references; más orquestación local de servicios/contenedores (sprout.toml).
Índice del Manual
| Capítulo | Español | English |
|---|---|---|
| 01. Primeros Pasos / First Steps | 01. Primeros Pasos | 01. First Steps |
| 02. TUI y Flujo Diario / Daily Workflow | 02. Interfaz TUI y Flujo Diario | 02. TUI & Daily Workflow |
| 03. Modos, Permisos y Sandbox | 03. Modos, Permisos y Sandbox OS | 03. Modes, Permissions & OS Sandbox |
| 04. Time-Travel, Vault y Forking | 04. Time-Travel, Snapshots y Forking | 04. Time-Travel, Snapshots & Forking |
| 05. Herramientas, Scent, Sprout y Skills | 05. Herramientas, Scent, Sprout y Skills | 05. Tools, Scent, Sprout & Skills |
| 06. Referencia CLI y Troubleshooting | 06. Referencia CLI y Troubleshooting | 06. CLI Reference & Troubleshooting |
Rutas de Lectura Recomendadas
- Si es tu primer día con
openonyx: empieza por 01. Primeros Pasos (o 01. First Steps) y después lee 02. Interfaz TUI y Flujo Diario. - Si trabajas con modelos locales (Ollama, vLLM, LM Studio): consulta la sección de proveedores locales en 01. Primeros Pasos,
--efforten 02. Interfaz TUI y los reintentos SSE en 06. Referencia CLI y Troubleshooting. - Si necesitas control estricto de seguridad o entornos corporativos: lee 03. Modos, Permisos y Sandbox OS.
- Si quieres experimentar con ramas de conversación y auditoría reproducible: lee 04. Time-Travel, Snapshots y Forking.
- Si usas microservicios locales o contenedores durante el desarrollo: consulta la sección de Sprout en 05. Herramientas, Scent, Sprout y Skills.
Requisitos Previos
- Rust
1.85o superior (el repositorio fija1.85.1enrust-toolchain.tomlconedition = "2024"). - Git instalado en el
PATH(necesario para checkpoints reversibles/undo,rewind,git_statusygit_diff). - Acceso a un LLM:
- Una clave de Google AI Studio (
GEMINI_API_KEY), o - Una clave de OpenAI / OpenRouter (
OPENAI_API_KEY), o - Una clave de Anthropic (
ANTHROPIC_API_KEY) para el proveedor nativo (--provider anthropic), o - Un servidor local compatible con OpenAI (
/v1/chat/completions) como Ollama, vLLM o LM Studio (sin API key requerida).
- Una clave de Google AI Studio (
- Opcional:
docker,nerdctlopodmansi vas a usar--sandbox strict-containero servicioskind = "container"ensprout.toml;bwrap(Bubblewrap) en Linux para aislamiento de sistema de archivos.
Otros Documentos del Repositorio
- README del repositorio (EN) · README en español
- README técnico de
open-onyx - README técnico de
onyx-workspace - Guía rápida operativa para agentes (
SKILL.md) - Historial de cambios (
CHANGELOG.md)
01. Primeros Pasos con openOnyx
En menos de 10 minutos pasarás de compilar openonyx a ejecutar tu primera sesión interactiva con streaming SSE, cambios supervisados con diff en color, modo PLAN/BUILD y reversión instantánea con /undo.
1. Compilar o instalar openonyx
Desde la raíz del repositorio OnYX:
# Compilación optimizada (recomendada para uso diario)
cargo build --release -p open-onyx
# O instalar en ~/.cargo/bin para invocar `openonyx` desde cualquier proyecto
cargo install --path open-onyx
Comprueba que el binario responde y revisa el estado de tu entorno:
openonyx --version
openonyx --help
openonyx doctor
Tip: si no instalaste el binario globalmente, puedes sustituir
openonyxporcargo run --release -p open-onyx --en todos los comandos de este manual, o usar./target/release/openonyx(Windows:.\target\release\openonyx.exe).
2. Configurar tu proveedor LLM
openonyx soporta de forma nativa Gemini (por defecto) y cualquier API compatible con OpenAI /v1/chat/completions (OpenAI, OpenRouter, Ollama, vLLM, LM Studio).
Opción A — Google Gemini (default)
Windows (PowerShell):
$env:GEMINI_API_KEY = "tu-api-key"
openonyx chat --auto-save
Linux / macOS (bash/zsh):
export GEMINI_API_KEY="tu-api-key"
openonyx chat --auto-save
Para elegir modelo o esfuerzo de razonamiento (low, medium, high):
openonyx chat --model gemini-2.5-pro --effort high --auto-save
Opción B — OpenAI / OpenRouter
Windows (PowerShell):
$env:OPENAI_API_KEY = "sk-..."
openonyx chat --provider openai --model gpt-4o --effort medium --auto-save
Linux / macOS:
export OPENAI_API_KEY="sk-..."
openonyx chat --provider openai --model gpt-4o --effort medium --auto-save
Con OpenRouter u otro proxy compatible:
openonyx chat --provider openai --api-base https://openrouter.ai/api/v1 --model anthropic/claude-sonnet-4 --auto-save
Opción C — Modelo local (Ollama, vLLM, LM Studio)
Cuando especificas --api-base (o OPENAI_API_BASE / OPENAI_BASE_URL), no necesitas configurar OPENAI_API_KEY.
Ollama:
openonyx chat --provider openai --api-base http://localhost:11434/v1 --model qwen2.5-coder:14b --effort low --auto-save
vLLM / LM Studio:
openonyx chat --provider openai --api-base http://localhost:8000/v1 --model Qwen/Qwen3-Coder-30B-A3B --auto-save
Consejo: usar
--auto-save(o fijarONYX_AUTO_SAVE=1en tu entorno) guarda automáticamente los snapshots y la transcripción.trjuntos dentro de.onyx/vault/<fecha>_<modelo>_<rama>/(ignorado automáticamente por Git) para que nunca ensucies la raíz del repo y siempre puedas usar/rewindo--resume.
3. Tu primera sesión interactiva (openonyx chat)
- Abre una terminal dentro de cualquier repositorio Git (o pasa
-w /ruta/al/proyecto). - Lanza
openonyx chat --snapshot-dir .snaps_demo --record demo.tr. - Verás la TUI con:
- Cabecera superior: emblema de estado, modo
[BUILD](o[PLAN]), badge de sandbox[SANDBOX:workspace], modelo y esfuerzo, y barra de telemetría (ctx, tokensin/cache/out/thinky coste). - Panel principal
Memory & Trace: conversación, llamadas a herramientas y respuestas streaming[stream] ...▍. - Caja de entrada inferior: tu prompt y accesos rápidos.
- Cabecera superior: emblema de estado, modo
Paso 1 — Explora sin riesgo en modo [PLAN]
Pulsa Tab para cambiar a [PLAN] (solo lectura; las herramientas mutantes quedan bloqueadas automáticamente). Escribe un objetivo de análisis y pulsa Enter:
Analiza la estructura de este repositorio y propón un plan para añadir una función de saludo en el módulo principal.
Observa cómo el agente usa herramientas de solo lectura (glob_files, scent_outline, code_search, fs_read, plan_update) sin pedirte aprobación. Si tu terminal tiene >= 100 columnas y el agente actualiza su lista de pasos, aparecerá el panel derecho Live Plan.
Paso 2 — Pasa a [BUILD] y aprueba cambios con diff en color
Pulsa Tab de nuevo para pasar a [BUILD] y escribe:
Implementa el cambio en el archivo principal y ejecuta los tests.
Cuando el agente invoque fs_edit, fs_write o shell_exec, la TUI se pausará en WaitingApproval:
- Verás qué agente pide la acción (
[agent #1 ...]). - Para ediciones de archivos, verás un diff unificado en color antes de tocar el disco.
- Puedes desplazarte por el historial mientras revisas con
Up/Down/PgUp/PgDn. - Pulsa
ypara aprobar onpara rechazar (si rechazas, el agente recibe la denegación y puede ajustar su propuesta).
Paso 3 — Deshacer el último cambio con /undo
¿No te convenció el último fs_edit o fs_write? Escribe en la caja de entrada:
/undo
openonyx restaura el checkpoint Git ligero capturado justo antes de la edición —sin modificar HEAD ni tu git add— y, si la operación fue un fs_write que creó un archivo nuevo no rastreado, lo elimina limpiamente sin tocar otros archivos tuyos.
Paso 4 — Salir guardando todo
Pulsa Esc o Ctrl+C. openonyx guarda el hito final (exit) en .snaps_demo/snapshots.onyxpack y cierra la transcripción demo.tr.
4. Reanudar, inspeccionar o reproducir después
Una vez cerrada tu primera sesión, prueba estos tres comandos sin gastar tokens extra:
# 1. Ver todos los hitos guardados y sus checkpoints Git
openonyx inspect .snaps_demo --list
# 2. Reproducir la sesión 100% offline (0 HTTP, 0 cambios en disco)
openonyx replay demo.tr
# 3. Reanudar exactamente donde lo dejaste
openonyx chat --resume .snaps_demo
5. Ejecución de un solo turno (headless)
Si prefieres ejecutar una tarea puntual sin TUI (por ejemplo desde un script o CI):
openonyx run "resume los cambios pendientes en git diff" --record run.tr --snapshot-dir .snaps_run
Al terminar, openonyx imprime el resultado final y una línea [openOnyx telemetry] con los tokens y coste de la ejecución.
← Índice del Manual · English Quickstart → · Siguiente: 02. Interfaz TUI y Flujo Diario →
02. Interfaz TUI y Flujo de Trabajo Diario
Este capítulo detalla cada componente visual de openonyx chat, cómo controlar el esfuerzo de razonamiento (--effort) y cambiar el objetivo LLM en caliente, cómo funciona la memoria multi-turno y el contexto escalonado (/compact), cómo navegar las cinco vistas efímeras F1..F5 (con la paleta Ctrl+K y /view), y cómo supervisar subagentes desde la vista F2 Agents (o el selector /agent).
1. Anatomía de la TUI
Al ejecutar openonyx chat, la pantalla se organiza en cuatro zonas bien definidas:
┌ F1 Chat · F2 Agents · F3 Sprout · F4 Plan & Diff · F5 Timeline · Esc:Quit ──────────────┐
│ openOnyx [BUILD] [SANDBOX:workspace] · gemini/gemini-2.5-pro (effort:high) │
│ goal: Refactoriza el parser… · phase: thinking / streaming… · #1 [root] [subagents:1] │
│ ⠋ Tab: Plan/Build · F2: Agents · /rewind · /fork · /services · Esc: quit │
└─ ctx: 24% · in: 18.4k (cache 12.1k) · out: 1.9k · think: 0.6k · ~$0.024 ────────────────┘
┌─ Memory & Trace (Agent #1 root) ───────────────────────┐┌─ Live Plan ───────────────────┐
│ [user] Refactoriza el parser... ││ [x] Inspeccionar AST │
│ [call] scent_outline {"path":"src/parser.rs"} ││ [>] Editar parser.rs │
│ [obs] @TOON v1 ... ││ [ ] Ejecutar cargo test │
│ [stream] Voy a ajustar la validación de rangos...▍ │├───────────────────────────────┤
│ ││ Services (Sprout) │
│ ││ [READY] postgres (5432) │
│ ││ [READY] api (8080) │
└────────────────────────────────────────────────────────┘└───────────────────────────────┘
┌─ [BUILD] Goal / Command (Enter send · Tab Plan/Build · F2 Agents · /rewind · /fork …) ──┐
│ > _ │
└─────────────────────────────────────────────────────────────────────────────────────────┘
Cabecera compacta (pestañas + título + cuerpo + telemetría)
- Tira de pestañas (fila superior, alineada a la derecha):
F1 Chat · F2 Agents · F3 Sprout · F4 Plan & Diff · F5 Timeline, con la vista activa en blanco negrita. Al final, la etiquetaEsc:QuitenF1 ChatoEsc:Backen las vistas efímeras; si hay una aprobación pendiente fuera deF1 Chat, se sustituye por el badge rojo [F1 Chat !APPROVAL] (aprobar a ciegas está prohibido: en las demás vistasy/nnunca aprueban ni deniegan). - Fila de título:
openOnyx [BUILD] [SANDBOX:workspace] · gemini/gemini-2.5-pro (effort:high)— badge de modo ([BUILD],[PLAN]o[EXPLORE]), badge de sandbox ([SANDBOX:workspace],[SANDBOX:strict]o[SANDBOX:off]), el tag[UNTRUSTED]si el workspace no está confiado y el objetivo LLM vivoprovider/model (effort:...), que se actualiza en caliente con/profile//provider//model//effort(sección 2.1). - Filas de cuerpo:
- Emblema Braille animado (
⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏, actualizado con throttle de 90 ms) cuando hay actividad en curso (thinking,acting,waiting_children, streaming SSE). - Objetivo y fase:
goal:del agente enfocado yphase:con la fase en curso, el ID/nombre/rol (#1 openonyx-1 [root]), los tags[subagents:N · bg:M · F2](o[N/M agents · F2]),[queued:N]y, si el guardado en sesión está activo (--auto-saveo--snapshot-dir), la etiqueta vivavault:<sesion>(que se actualiza automáticamente al crear ramas con/forko/rewind). - Atajos rápidos o tira de agentes: recordatorio compacto (
Tab: Plan/Build · F2: Agents · /rewind · /fork · /services · Esc: quit) o, con múltiples agentes, la tira compacta de agentes en una línea.
- Emblema Braille animado (
- Borde inferior (Telemetría en vivo):
- Ocupación aproximada de ventana de contexto (
ctx: <1%oXX%). - Contadores acumulados de sesión del proveedor:
in,cache(tokens servidos desde prompt cache),outythink(tokens de razonamiento cuando el proveedor los reporta). - Coste estimado (
~$0.024) para modelos cloud conocidos, olocalcuando usas un--api-basepersonalizado. - Esta telemetría vive fuera del grafo EAV para no alterar nunca el determinismo de ticks, snapshots ni replay.
- Ocupación aproximada de ventana de contexto (
Panel Memory & Trace y navegación por historial
- Muestra la conversación completa del agente enfocado: prompts de usuario, llamadas a herramientas (
[call]), observaciones ([obs]), respuestas del modelo, notas del sistema ([system]) y la vista previa SSE en tiempo real ([stream] ...▍, renderizada enpump_idlesin consumir ticks). - Desplazamiento suave: usa
Up,Down,PgUp,PgDn,Home,End,Ctrl+UyCtrl+Dincluso mientras hay una aprobación pendiente. Cuando subes en el historial, aparece el indicador[SCROLLED -N lines | End to follow]; pulsarEndo enviar un nuevo mensaje devuelve el seguimiento automático al final.
Paneles laterales automáticos (>= 100 columnas)
Cuando tu terminal tiene al menos 100 columnas de ancho, la zona central se divide en 70% (Memory & Trace) y 30% (panel derecho):
Live Plan: aparece automáticamente cuando el agente registra pasos conplan_update([x]completado,[>]en progreso,[ ]pendiente).Services (Sprout): aparece cuando existe unsprout.tomlválido en el workspace, mostrando el estado coloreado de cada servicio ([READY],[STARTING],[PENDING],[FAILED],[OFF]).- Si ambos están activos a la vez, la columna derecha se divide
50%/50%verticalmente.
Panel de aprobación con diff unificado (y / n)
Cuando cualquier agente solicita una herramienta mutante (fs_write, fs_edit, shell_exec, service_start, service_stop, service_exec) que requiere confirmación:
- El panel de aprobación identifica explícitamente al solicitante:
[agent #id name](muy útil cuando delegas trabajo a subagentes). - Para
fs_writeyfs_edit(incluyendo ediciones atómicas multi-hunk), se calcula una vista previa de diff unificado en color antes de escribir nada en disco. - Pulsa
ypara aprobar onpara rechazar. - Solo desde
F1 Chat: en las vistas efímerasF2..F5las teclasy/nnunca aprueban ni deniegan; la tira de pestañas muestra el badge[F1 Chat !APPROVAL]para recordarte volver aF1a revisar el diff y la línea# impact:.
2. Control del Esfuerzo de Razonamiento (--effort)
Puedes modular cuánto tiempo y tokens dedica el modelo a razonar internamente:
| Valor | Gemini (thinkingLevel) | OpenAI-compatible (reasoning_effort) | Uso recomendado |
|---|---|---|---|
low | LOW | low | Tareas rápidas, consultas de lectura, modelos locales ligeros |
medium | MEDIUM | medium | Balance diario de edición, debugging y refactorizaciones |
high | HIGH | high | Diseño arquitectónico, bugs sutiles, auditorías complejas |
Se puede indicar por flag o por variable de entorno (precedencia: --effort > ONYX_EFFORT > GEMINI_THINKING_LEVEL / OPENAI_REASONING_EFFORT):
openonyx chat --effort high
# o mediante variable de entorno:
export ONYX_EFFORT=medium
Para
anthropic: el esfuerzo se traduce en un presupuesto de extended thinking (thinking.budget_tokens:low2048 /medium8192 /high16384 tokens) cuando no se fija uno explícito. Puedes acotarlo con--thinking-budget <n>(oANTHROPIC_THINKING_BUDGET;0= off, rango1024..=60000), que además elevamax_tokenspor encima del presupuesto. El proveedor soporta además prompt caching (cache_control: ephemeralen el sistema y la última definición de tool) y reintentos automáticos ante429/529(capítulo 06).
2.1 Objetivo LLM en caliente (/profile, /provider, /model, /effort)
Más allá del esfuerzo, el objetivo LLM completo (proveedor, modelo, api_base y esfuerzo) es conmutable en caliente sin reiniciar la sesión:
- Perfiles: bloques
[[llm_profiles]]en.onyx/config.toml(workspace confiado) conid,provider(gemini|openai|anthropic),model,effort,api_baseopcional yapi_key_envopcional. Nunca se admiten claves literales en el archivo (detalles en el capítulo 03). - Comandos slash:
/profile [id]lista o aplica un perfil,/provider <gemini|openai|anthropic>,/model <name>y/effort <auto|low|medium|high>. El cambio se aplica en la siguiente frontera de tick y queda sellado en la transcripciónONYXTR2(replay determinista). - Cabecera viva: la fila de título pasa a mostrar
provider/model (effort:...)del objetivo actual en lugar del de arranque. - Paleta
Ctrl+K: alternativa sin teclear — filtras perfiles, proveedores y esfuerzos y ejecutas conEnter(las acciones LLM pasan por el bus determinista, igual que si las tecleas; un perfil sin credenciales se muestra comounavailablecon su motivo y no es seleccionable). - Web UI (
openonyx serve): el botón LLM target (subtítulo de la marca) abre un diálogo modal con perfil/modelo/esfuerzo y botones Apply/Cancel, sin exponer credenciales al navegador.
Las credenciales nunca viven en el config: cada perfil resuelve su clave por
api_key_env(o la variable estándar del proveedor →ONYX_API_KEY). Un perfil sin clave o conapi_baserechazada se lista comounavailablecon su motivo accionable.
3. Conversaciones Multi-Turno, Guardia de Raíz Activa y /new
Continuación automática (continue_agent)
Al terminar un turno (Settled), escribir un nuevo mensaje y pulsar Enter no crea un agente amnésico: openonyx reactiva al mismo agente raíz mediante continue_agent, conservando toda su rel_memory con contador de pasos monótono.
Cola de seguimiento mientras el agente trabaja (queued:N)
Si el agente raíz está ocupado (thinking, acting, waiting_children o waiting_approval), puedes escribir tu siguiente instrucción y pulsar Enter: en lugar de crear un segundo agente raíz que compita por el workspace, la TUI la encola automáticamente (queued:N en cabecera y borde inferior, previsualizada si la entrada está vacía, y limpiable en cualquier momento con Ctrl+X) y la despacha al instante en cuanto el turno termina. Los comandos inmediatos (/agent, /mode, /services, /service, /undo) siguen ejecutándose al momento.
Autocompletado /, @archivo, cursor e historial de entrada
- Cursor UTF-8 visible: muévete dentro del prompt con
Left,Right,Home,End,BackspaceyDelete. - Historial de prompts: navega tus prompts anteriores con
Alt+Up/Alt+Down(oCtrl+P/Ctrl+N), conservando automáticamente tu borrador si vuelves abajo. - Popup
/: al empezar con/, aparece un menú flotante con todos los comandos slash y su descripción (↑/↓,Tab/Enterpara aceptar,Escpara cerrar). - Popup
@: al escribir@al inicio de una palabra (p. ej.revisa @tui), se filtran en tiempo real las rutas del workspace (ignorando.git,target,node_modulesy.onyx/vault) y al pulsarTab/Enterse inserta la ruta relativa limpia.
Empezar una conversación limpia (/new)
/new: marca que el siguiente prompt creará un agente raíz limpio desde cero (sin arrastrar historial de la tarea anterior)./new <objetivo>: crea y lanza inmediatamente un nuevo agente raíz con<objetivo>y enfoca la vista automáticamente en él.
4. Contexto Escalonado y /compact [focus]
Para evitar que sesiones largas agoten la ventana de contexto o disparen el coste de tokens, openonyx aplica un motor de contexto escalonado (Tier 0 / Tier 1 / Tier 2) compartido por Gemini y OpenAI:
- Tier 0 (Completo): las últimas 10 observaciones de herramientas se envían íntegras al modelo.
- Tier 1 (Resumen con coordenadas): observaciones antiguas de
fs_read,scent_outline,scent_impact,code_search,glob_filesyshell_execse comprimen determinísticamente preservando rutas, rangos de líneas y códigos de salida, manteniendo prefijos estables para maximizar el prompt caching. - Tier 2 (Compactación
/compacty auto-compactación): al llegar al umbral automático (80%de presupuesto de contexto) o al invocar manualmente/compact [focus],CommandSpawnerSysteminserta un límite[session_summary]verificado en la memoria del agente.
Cómo sacar partido a /compact [focus]
/compact
/compact autenticacion jwt y middleware
Cuando proporcionas un [focus]:
openonyxrescata automáticamentefiles_foundyfocus_matchesrelevantes a las palabras clave desde turnos anteriores.- El porcentaje
ctx:baja de inmediato en el siguiente turno. - Se guarda el hito
cmd:/compactensnapshots.onyxpack. - No se pierde nada: los ticks anteriores al
/compactsiguen intactos en el grafo y ensnapshots.onyxpackparainspect,replayyrewind.
5. Vistas Modulares F1..F5, Paleta Ctrl+K y /view
Además de F1 Chat (traza, paneles laterales, input y aprobaciones), la TUI expone cuatro vistas efímeras a las que saltas con la tecla funcional, /view <nombre> o la paleta Ctrl+K:
| Vista | Tecla | Slash | Contenido |
|---|---|---|---|
F1 Chat | F1 | /view chat | Traza Memory & Trace, paneles Live Plan / Services (Sprout), input y aprobaciones |
F2 Agents | F2 | /view agents | Agentes del grafo + jobs asíncronos [bg] (con badge → <driver> si el worktree lo corre un harness CLI externo) |
F3 Sprout | F3 | /view sprout | Servicios sprout.toml (badges de estado) + logs en vivo del servicio seleccionado |
F4 Plan & Diff | F4 | /view plan | Plan activo (ws.plan.text) arriba + ledger de efectos Git (tick, tool, target, reversibilidad, (undone)) abajo |
F5 Timeline | F5 | /view timeline | Hitos de snapshots.onyxpack (tick, tag, tamaño, checksum) para /rewind / /fork |
- Navegación 100 % efímera: cambiar de vista no escribe en el grafo, no genera eventos de bus ni avanza ticks — es solo un "cristal" distinto sobre el mismo estado determinista.
F2 Agents:Up/Downselecciona (el agente enfocado lleva el marcador*),Enterenfoca la trazaMemory & Tracedel agente y vuelve aF1 Chat,Escvuelve aF1 Chat.F3 Sprout:Up/Down/PgUp/PgDnnavegan servicios;s/x/r/a(start/stop/restart/all) yf(follow de logs) están bajo gate: en modoPLAN/EXPLOREo con workspace[UNTRUSTED]la cabecera de la vista muestraMUTATIONS BLOCKEDy la acción se rechaza con un aviso.F4 Plan & Diff:Up/Downdesplazan el ledger de efectos Git.F5 Timeline:Up/Downseleccionan hito,Enterlanza/rewind <tick>,flanza/fork.Esc: cierra popups o la paleta si están abiertos; enF1 Chatsale limpiamente; enF2..F5vuelve aF1 Chat(la etiqueta de la tira de pestañas diceEsc:QuitoEsc:Back)./view <chat|agents|sprout|plan|timeline>(case-insensitive): se intercepta enEntera nivel de TUI — 0 eventos de bus, 0 ticks, 0 escrituras al grafo./viewsin argumento muestra el usage; un nombre desconocido muestra un aviso transitorio.- Paleta
Ctrl+K: popup centrado (Ctrl+K Palette — type to filter) con tres grupos — VIEW (F1..F5), LLM (perfiles[[llm_profiles]], proveedores y esfuerzos) y AGENT (agente por ID/nombre). Escribe para filtrar (todos los caracteres imprimibles filtran —j/kincluidos, nunca navegan),Up/Down(oCtrl+P/Ctrl+N) eligen,Enterejecuta yEsc/Ctrl+Kcierran. Tiene prioridad máxima (salvoCtrl+C) y traga todas las teclas mientras está abierta; las acciones LLM se envían por el bus determinista y quedan selladas enONYXTR2, igual que tecleadas.
6. Flujo Multi-Agente: Subagentes, Vista F2 Agents y /agent
El agente raíz puede delegar subtareas de dos formas: subagentes síncronos del grafo (spawn_agent, que comparten la workspace y a los que el padre espera) y jobs asíncronos en worktrees Git aislados (spawn_subagent / /spawn, capítulo 05).
- Presupuesto seguro por defecto: los subagentes sincrónos heredan un techo por defecto de
32pasos (DEFAULT_SUBAGENT_MAX_STEPS, modificable si el padre pasamax_stepsexplícitamente en los argumentos JSON despawn_agent), evitando bucles infinitos en modelos locales. Mientras existen hijos activos, el padre pasa aWaitingChildren. - Inspección en vivo con la vista
F2 Agents: pulsaF2en cualquier momento para saltar a la vista Agents (a pantalla completa):- Lista todos los agentes del grafo (raíz y subagentes) con ID, nombre, rol (
root/sub), estado actual y objetivo. - También lista los jobs asíncronos
[bg]con su estado (running,done,merged,failed), rama de worktree y, si el job lo corre un harness externo, el badge→ <driver>. - Navega con
Up/Down, pulsaEnterpara enfocar la trazaMemory & Tracedel agente (vuelve aF1 Chat) oEscpara volver aF1 Chat.
- Lista todos los agentes del grafo (raíz y subagentes) con ID, nombre, rol (
- Atajos alternativos:
/agent(o/agents): abre el popup Agent Selector centrado (o rota al siguiente agente si solo existe uno)./agent <id|nombre>: salta directamente a un agente concreto (por ejemplo/agent 1o/agent researcher).Ctrl+K: la paleta también lista los agentes;Enterenfoca y vuelve aF1 Chat.Ctrl+Tab: rota rápidamente al siguiente agente enfocado (alias dependiente del terminal;F2,/agenty la paleta funcionan en todos los terminales).
- Drivers externos desde la Web UI: en
openonyx serve, el selector Subagent driver permite elegir un[[external_drivers]]declarado; al enviar texto libre con un driver no nativo, el navegador emite/spawn --driver <id> <texto>(capítulo 05).
7. Depurador Temporal Interactivo (TimeFreeze, SDD-07)
TimeFreeze permite pausar la sesión en cualquier tick y examinarla paso a paso sin gastar tokens ni tocar disco: las fronteras de tick viven en un anillo RAM (los hitos en disco de --snapshot-dir se superponen como referencias) y todo el estado es 100 % efímero hasta que confirmes una bifurcación (/go con el cursor anclado en el pasado crea el fork; sin confirmación no se escribe nada).
Congelar, scrubear y salir
| Acción | Cómo |
|---|---|
| Congelar / descongelar en el cursor | Ctrl+T o /time (toggle efímero) |
| Scrubear −1 / +1 sobre ticks disponibles | Alt+← / Alt+→ (mirar el pasado auto-congela) |
| Volver al presente sin cerrar la app | Esc mientras TIME FROZEN (segundo Esc en vivo: sale) |
Ir a un tick concreto (hitos [pack:*], [ram], (present)) | F5 Timeline → Down/Up → Enter |
Bajo freeze aparece el banner ámbar (⏸ TIME FROZEN · tick X / present Y + archivos que se revertirían al bifurcar, solo RAM) y el prompt plano se bloquea: un turno desordenado rompería la bit-a-bit del replay. Las vías de escape (/… y !…) siguen funcionando siempre, incluso con el agente ocupado en Thinking (breakpoint pre-LLM): se ejecutan inmediatas, sin colas.
Primitivas 0-tokens y cirugía del grafo congelado
| Comando | Qué hace |
|---|---|
/step [n] | Avanza n ticks deterministas con 0 LLM (default 1; funciona congelado) |
/step-llm | Un solo turno de LLM: gate + bifurcación si aplica + recongelado al responder |
/go (alias /unfreeze) | Bifurca desde el cursor si mira el pasado y reanuda en el presente |
! <cmd> | Ejecuta un comando shell determinista en sandbox y sella el resultado (0 red, 0 disco) |
/read <ruta> [a..b] | Lee un archivo (o rango de líneas) a memoria, 0 tokens, frozen-safe |
/inject <texto> | Inyecta una memoria user sellada en la línea temporal (0 tokens) |
/graph inspect [agent|mem|ws] | Informe read-only del grafo congelado (memorias con mem_seq, agentes, workspace) |
/graph drop-mem <seq|a..b> | Elimina memorias por mem_seq sin avanzar el tiempo |
/graph edit-mem <seq> <texto> | Edita una memoria existente in-place |
/graph set-goal <texto> | Cambia el objetivo del agente raíz en el grafo congelado |
Estas primitivas se sellan en ONYXTR2 (/__onyx_det_*): el replay offline las reproduce bit-a-bit con 0 I/O y 0 red. En la vista Web/PWA (openonyx serve) hay paridad completa: la pill #tick-pill abre la misma barra ámbar, POST /api/v1/time/scrub aplica scrubs efímeros, los prompts planos bajo freeze reciben 409 Conflict accionable y las memorias del agente raíz exponen botones ✎/× — ver capítulo 04.
Non-goal: los efectos de Sprout (servicios/contenedores) y de los servidores MCP son efectos externos de proceso, no mutaciones del grafo:
TimeFreezeno los rebobina (ni los revierte al bifurcar).
8. Resumen de Atajos y Comandos en chat
| Tecla / Comando | Acción |
|---|---|
Enter | Envía objetivo, seguimiento al agente raíz o comando slash |
Tab | Alterna en caliente entre [BUILD] y [PLAN] |
F1..F5 | Cambia de vista efímera (Chat, Agents, Sprout, Plan & Diff, Timeline) |
Ctrl+K | Abre la paleta de comandos (vistas + slash LLM + agentes); escribe para filtrar, Enter ejecuta |
Ctrl+Tab | Rota rápidamente el agente enfocado (alias opcional de F2 / /agent) |
y / n | Aprueba o rechaza la herramienta mutante pendiente (solo en F1 Chat; en otras vistas la TUI avisa a pulsar F1) |
Up/Down/PgUp/PgDn/Home/End/Ctrl+U/Ctrl+D | Desplaza el historial Memory & Trace |
Alt+← / Alt+→ | TimeFreeze: scrub del cursor −1/+1 sobre ticks disponibles (auto-congela al mirar el pasado) |
Ctrl+T | TimeFreeze: toggle de freeze en el cursor / volver al presente (efímero, 0 disco) |
Esc | Cierra popup/paleta; bajo TIME FROZEN vuelve al presente sin salir; en F2..F5 vuelve a F1 Chat; en F1 Chat sale limpiamente guardando snapshot y transcripción |
Ctrl+C | Sale limpiamente (snapshot de salida y transcripción, si están configurados) |
/view <chat|agents|sprout|plan|timeline> | Cambia de vista desde el prompt (efímero: 0 eventos de bus, 0 ticks, 0 grafo) |
/agent [id|name] | Abre el selector de agentes o enfoca el agente indicado |
/mode [plan|build|explore] | Cambia de modo o alterna PLAN ↔ BUILD |
/undo | Revierte el último checkpoint Git reversible (y limpia archivos nuevos de fs_write) |
/rewind [tick] | Lista hitos o retrocede en caliente a <tick> creando un fork seguro |
/fork [name] | Crea una rama de snapshots hasta el tick actual en un directorio hermano |
/time | TimeFreeze: alterna el freeze en el cursor actual (efímero, 0 disco) |
/go (alias /unfreeze) | TimeFreeze: bifurca si el cursor mira el pasado y reanuda en el presente |
/step [n] | TimeFreeze: n ticks deterministas con 0 LLM (default 1; frozen-safe) |
/step-llm | TimeFreeze: exactamente un turno de LLM (gate + bifurcación + recongelado) |
! <cmd> | Shell determinista en sandbox con resultado sellado en ONYXTR2 (frozen-safe) |
/read <ruta> [a..b] | Lee un archivo (o rango) a memoria, 0 tokens (frozen-safe) |
/inject <texto> | Memoria user sellada en la línea temporal, 0 tokens (frozen-safe) |
/graph <inspect|drop-mem|edit-mem|set-goal> | Inspección read-only o cirugía del grafo congelado (memorias por mem_seq, objetivo) sin avanzar el tiempo |
/compact [focus] | Compacta turnos anteriores rescatando archivos y coincidencias del foco |
/services | Muestra estado @TOON v1 de servicios definidos en sprout.toml |
/service <start|stop|logs> <id|all> [tail] | Controla servicios Sprout directamente desde la TUI |
/new [goal] | Prepara o lanza un agente raíz limpio |
/profile [id], /provider <gemini|openai>, /model <name>, /effort <auto|low|medium|high> | Cambian el objetivo LLM en caliente (sección 2.1) |
/spawn [--driver <id>] <goal> | Lanza un job asíncrono en worktree Git aislado (capítulo 05) |
/subagents | Lista los jobs asíncronos [bg] (estado, rama, archivos tocados) |
/merge <job_id> | Fusión 3-way del worktree del job (governance Ask/Deny, capítulo 03) |
/discard <job_id> | Cancela el job y elimina su worktree y rama temporal |
← 01. Primeros Pasos · Índice · Siguiente: 03. Modos, Permisos y Sandbox OS →
03. Modos de Trabajo, Permisos y Sandbox OS
openonyx aplica defensa en profundidad sobre todo lo que hace el agente: modos de workspace, reglas declarativas .onyx/config.toml, protección del Control Plane, sanitización de entorno (env_clear()), aislamiento a nivel de sistema operativo y supervisión RAII de procesos.
1. Modos de Workspace: PLAN, BUILD y EXPLORE
El modo activo (ws.mode) se almacena dentro del grafo EAV y se graba en las transcripciones ONYXTR2, de modo que rewind y replay lo restauran exactamente.
| Modo | Lectura / Búsqueda / AST | Mutaciones (fs_write, fs_edit, shell_exec, service_start/stop/exec) | Uso recomendado |
|---|---|---|---|
BUILD (default) | Permitido | Permitido con aprobación (o según reglas .onyx/config.toml). fs_edit exige lectura previa del archivo con fs_read. | Implementación, refactorización, ejecución de tests. |
PLAN | Permitido | Bloqueado incondicionalmente (incluso con allow en config.toml o --auto-approve). | Análisis de arquitectura, diseño de planes, revisión de PRs. |
EXPLORE | Permitido | Bloqueado incondicionalmente. | Exploración rápida de solo lectura en repositorios desconocidos. |
Tools MCP dinámicas: aunque un tool
mcp__<server>__<tool>no mutee el filesystem local, un servidor MCP remoto puede ejecutar procesos o red fuera del control deopenonyx; por eso se trata igual que una mutación y quedaDenyenPLAN/EXPLORE(capítulo 03, sección 2.8).
Cómo cambiar de modo en chat
- Pulsa
Tabpara alternar en caliente entre[BUILD]y[PLAN]. - O usa el comando slash explícito:
/mode plan,/mode build,/mode explore(o/modesin argumentos para alternarPLAN↔BUILD).
2. Permisos Declarativos (.onyx/config.toml)
Puedes definir reglas granulares en dos ubicaciones que se cargan y fusionan automáticamente:
- Global de usuario:
~/.onyx/config.toml - Por proyecto:
<workspace>/.onyx/config.toml
Regla de seguridad: un proyecto nunca puede eliminar una regla
denydefinida en tu~/.onyx/config.tomlglobal.
Precedencia: deny > ask > allow
deny: bloquea la herramienta de forma incondicional, incluso si ejecutasopenonyxcon--auto-approve. Solo puede omitirse pasando explícitamente--ignore-deny.ask: fuerza confirmación interactiva (y/n), prevaleciendo sobreallowa igual o mayor especificidad.allow: auto-aprueba una herramienta/patrón específico sin interrumpirte (siempre que estés en modoBUILD; enPLAN/EXPLORElas mutaciones siguen bloqueadas). Unallowmás específico (p. ej.shell_exec(cargo test*)) vence a un comodín genéricoask(shell_exec(*)).
Ejemplo completo de .onyx/config.toml
[permissions]
# Bloqueos absolutos (ni siquiera --auto-approve los salta)
deny = [
"shell_exec(rm -rf*)",
"shell_exec(git push*)",
"shell_exec(curl*)",
"fs_write(.env*)",
]
# Auto-aprobar comandos de verificación seguros en modo BUILD
allow = [
"shell_exec(cargo check*)",
"shell_exec(cargo test*)",
"shell_exec(cargo clippy*)",
"shell_exec(cargo fmt --all -- --check)",
]
# Requerir confirmación explícita para cualquier otro shell_exec o escritura
ask = [
"shell_exec(*)",
"fs_write(*)",
"fs_edit(*)",
]
[sandbox]
# "workspace-write" (default) | "strict-container" | "off"
mode = "workspace-write"
# "offline" (default) | "localhost" | "unrestricted"
network = "offline"
# Variables extra permitidas tras env_clear() (nunca pases API keys)
env_passthrough = ["RUST_LOG", "RUST_BACKTRACE"]
# Rutas adicionales de solo lectura fuera del workspace (opcional)
allow_read_paths = []
# Límites de recursos para subprocesos
max_memory_mb = 4096
max_pids = 128
# Imagen OCI cuando mode = "strict-container" (opcional)
# container_image = "rust:1.85-slim"
[impact]
# Scent-Heated Approval: escala Allow -> Ask si un diff toca símbolos públicos con callers
enabled = true
max_hops = 2 # acotado 1..=4
ask_heat_bp = 2500 # umbral para símbolos pub scope:src (basis points 0..=10000)
hard_ask_bp = 8000 # umbral duro para cualquier símbolo con alto fan-out
[verify]
# Verify-on-Edit: tras cada fs_edit/fs_write exitoso ejecuta las reglas cuya glob
# empareja el archivo editado (sección 2.9). Desactivado por defecto.
on_edit = true
max_secs = 20 # timeout por defecto por regla (acotado 1..=120)
[[verify.rules]]
glob = "**/*.rs"
command = "cargo test --workspace"
# max_secs = 60 # timeout propio de la regla (opcional)
Monotonía de Scent-Heated Approval:
[impact]solo puede subir una decisiónAllow → Asky mostrar la línea# impact: N callers, H hops, scope:src(pub) [heat Xbp]sobre el diff en TUI/CLI. Nunca anula undeny, nunca baja unaskaallow, y degrada limpiamente a política estática si el archivo no está indexado oenabled = false.
2.5. Workspace Trust (~/.onyx/trusted_workspaces.toml)
Para proteger frente a repositorios clonados o PRs externos con configuraciones maliciosas (Indirect Prompt Injection + allow = ["shell_exec(*)"] o sprout.toml arbitrario), openOnyx fija los hashes blake3 de .onyx/config.toml y sprout.toml por workspace en ~/.onyx/trusted_workspaces.toml:
- Repositorio limpio (sin
.onyx/config.tomlnisprout.toml): sin fricción (no-project-config). - Repositorio no confiado o modificado (
untrusted/modified, badge[UNTRUSTED]en TUI):.onyx/config.tomldel proyecto solo puede restringir (deny/ask, sandbox/impact más estrictos); se ignoran sus reglasallow,env_passthrough,allow_read_paths,container_imagey cualquier relajación de[sandbox]/[impact].sprout.tomlbloquea la ejecución de servicios (service_start,service_exec,stop_cmd) hasta aprobación explícita.
- Comandos de confianza:
openonyx trust(aprueba el workspace actual),openonyx trust check,openonyx trust list,openonyx trust revoke, flag de sesión--trust-workspaceo/trust [status|revoke]en la TUI.
2.6. Perfiles LLM ([[llm_profiles]])
El objetivo LLM (proveedor, modelo, api_base, esfuerzo) puede declararse en .onyx/config.toml como bloques [[llm_profiles]] y conmutarse en caliente con /profile / /provider / /model / /effort (capítulo 02, sección 2.1):
[[llm_profiles]]
id = "local-ollama"
provider = "openai"
model = "llama3.1:70b"
effort = "medium"
api_base = "http://localhost:11434/v1"
# api_key_env = "OLLAMA_API_KEY"
- Campos:
id(único),provider(gemini|openai|anthropic),model,effort(auto|low|medium|high),api_baseopcional yapi_key_envopcional. Claves desconocidas o duplicadas son error de parse accionable. - Nunca claves literales: un
api_keyliteral en el bloque es rechazado por el parser con un error que indica usarapi_key_env(y el mensaje no repite el valor de la clave). Las credenciales siempre se resuelven de variables de entorno (api_key_env→ variable estándar del proveedor →ONYX_API_KEY). api_basevalidado al registro: con la misma política que--api-base(http://solo en loopback; hosts remotos exigenhttps://; hosts no oficiales requieren--allow-custom-auth-host).- Gate de Trust: un workspace no confiado ignora sus bloques
[[llm_profiles]]y muestra la advertenciaignored N [[llm_profiles]] block(s); run openonyx trust or /trust to approve. Con workspace confiado, la precedencia es global (~/.onyx/config.toml) < proyecto (fusion replace-by-id). - Disponibilidad: un perfil sin clave resuelta o con
api_baserechazada se lista comounavailablecon motivo accionable (/profile, paletaCtrl+Ky selector Web). La TUI y la Web solo exponen metadatos (public_snapshot): proveedor, modelo, esfuerzo y motivo — nunca claves.
2.7. Harnesses CLI externos ([[external_drivers]])
Los jobs asíncronos spawn_subagent / /spawn (capítulo 05) pueden ejecutarse fuera del motor OnYX, delegando el trabajo a un harness CLI externo declarado en .onyx/config.toml:
[[external_drivers]]
id = "opencode"
bin = "opencode"
args = ["run", "--model", "qwen38-27b"]
# prompt_transport = "stdin" # "stdin" (default) | "arg" | "temp_file"
# prompt_flag = "--prompt-file" # para "temp_file" (o placeholder {prompt_file} en args)
timeout_secs = 600
allowed_env = []
# inherit_home = true # si el CLI necesita config/OAuth del HOME real
# network_allowlist = ["api.ejemplo.com"]
- Campos:
id(charset[a-z0-9_-]),bin(resuelto enPATH/PATHEXT),args(argumentos fijos),prompt_transport(stdinrecomendado y default;argrechazado en Windows si el binario resuelve a un wrapper.cmd/.bat;temp_filepara prompts grandes, fuera del índice Git),prompt_flag,timeout_secs,allowed_env(whitelist de variables para el hijo) einherit_home(defaultfalse). - Gate de Trust: un workspace no confiado no puede lanzar drivers externos (
Denyabsoluto:requires a trusted workspace). - Aprobación por defecto
Ask:spawn_subagentcon driver externo nunca auto-aproba: sin reglasask/allowexplícitas la decisión esAsk; puedes fijarla conallow = ["spawn_subagent(opencode)"]oask/denycon el mismo patrón (undeny spawn_subagent(opencode)bloquea ese driver aunque hayaallow). - Aislamiento del proceso: el prompt se entrega sin inyección de shell (stdin/argv único/archivo temporal); el entorno del hijo pasa por
env_clear()+allowed_env; el proceso queda asignado a unProcessJobdesde elspawn(sitimeout_secsvence o se cancela el job, muere el árbol entero; en Windows hay fallbacktaskkill /F /T /PID); y el log completo se sella en.onyx/vault/subagent-logs/<job_id>.logpasando porscrub_secrets. - Red declarativa (
network_allowlist): es una gobernanza declarativa: con--sandbox strict-containerse enforce en el contenedor; en los demás perfiles es advisory (eldoctorlo avisa). Un allowlist vacío equivale aLocalhostOnly; con allowlist, el sandbox no inyecta variables*_OFFLINE(el harness necesita llegar a su API). - Merge forzadamente
Ask: aunque tus permisos auto-aprobieran,subagent_mergede un job con driver externo exige aprobación explícita (ExternalDriverApprovalPolicy).
2.8. Servidores MCP ([mcp.servers.<name>])
openonyx puede conectar servidores Model Context Protocol (MCP) declarados en config.toml (global ~/.onyx/config.toml y, con workspace confiado, <workspace>/.onyx/config.toml):
[mcp.servers.github]
transport = "stdio"
command = "npx"
args = ["-y", "@modelcontextprotocol/server-github"]
# env = { GITHUB_TOKEN = "${GITHUB_TOKEN}" } # referencias ${VAR} al lanzar el proceso
timeout_secs = 20 # default 20
# enabled = true # default true
[mcp.servers.docs]
transport = "http"
url = "https://mcp.ejemplo.com/sse"
# headers = { Authorization = "Bearer ${MCP_DOCS_TOKEN}" }
- Campos:
transport("stdio"concommand/args/env, o"http"conurl/headers),timeout_secs(default20s por llamada JSON-RPC) yenabled(defaulttrue). Los nombres de servidor no pueden contener__(reservado para el prefijomcp__<server>__<tool>). Las referencias${ENV_VAR}se expanden solo al lanzar la request/proceso (nunca se loguean ni persisten) yAuthorization/X-Api-Keyenheadersexigen${VAR}. - Fusión y gate de Trust: fusión replace-by-name con precedencia
global < workspace; un workspace no confiado ignora sus[mcp.servers.*]con la advertenciaMCP config in ... ignored: workspace is not trusted (use --trust-workspace or openonyx trust), mientras que la configuración global siempre aplica. - Naming y aprobación: cada tool descubierta (
tools/list) se expone al LLM comomcp__<server>__<tool>conrequires_approval = true: siempre pide aprobación interactiva enBUILD, salvo que una reglaallowmás específica diga lo contrario (p. ej.allow = ["mcp__github__search_repos"]oallow = ["mcp__github__*"]);ask/denycon glob también funcionan (deny = ["mcp__*"]bloquea todo MCP). PLAN/EXPLORE=Deny: en esos modos cualquiermcp__*queda bloqueado incondicionalmente (un servidor remoto ejecuta procesos/red fuera del sandbox).- Aislamiento de fallos: un servidor caído no aborta la sesión: se reporta
[openOnyx mcp] server \` unavailable: ... y el resto de la sesión sigue; cada servidor expone su estado paraopenonyx doctor`. - Seguridad de la sesión stdio: JSON-RPC 2.0 con hilo lector dedicado, timeout real por llamada (
mpsc::recv_timeout), línea destdoutacotada a 4 MiB y limpieza del árbol de procesos conProcessJobal fallar (Windows y Unix). - Salidas saneadas: los resultados de
tools/cally los errores de descubrimiento pasan portruncate_utf8+scrub_secretsantes de llegar al LLM o a la transcripción. openonyx doctor: audita cada servidor declarado con un handshake acotado a 5 s (min(timeout_secs, 5)):Connected/Disabled→[CHECK], fallo →[ERR]accionable (mensaje ya scrubbeado), workspace no confiado →[WARN]sin descubrimiento de workspace.replay0-I/O: al reproducir una transcripciónONYXTR2no se contacta con ningún servidor: los toolsmcp__*se reconstruyen desde la propia transcripción (extract_mcp_tools_from_transcript), sinload_mcp_registry.
2.9. Verify-on-Edit ([verify] / [[verify.rules]])
El Verify-on-Edit cierra el bucle edit → verificar dentro del turno del agente: tras cada fs_edit/fs_write exitoso, openonyx ejecuta los comandos cuyas reglas emparejan el archivo editado e inyecta el resultado al final de la observación del tool, para que el modelo corrija el error antes de terminar el turno.
[verify]
on_edit = true # default false: opt-in explícito, 0 overhead sin configurar
max_secs = 20 # timeout por defecto por regla (acotado 1..=120)
[[verify.rules]]
glob = "**/*.rs" # glob de ruta relativa (compile_glob_regex)
command = "cargo test --workspace"
# max_secs = 60 # timeout propio de la regla (opcional)
[[verify.rules]]
glob = "src/**"
command = "pnpm test"
- Alcance de cada regla: la regla se dispara si la
globempareja el archivo editado o (cuando hay índice Scent) un archivoscope:testalcanzable por impacto AST en ≤ 2 hops; si el workspace no está indexado, solo empareja la ruta editada. - Ejecución: cada
commandpasa por la misma tubería de sandbox deshell_exec(prepare_sandboxed_shell_command+configure_process_isolation+ProcessJobRAII +env_clear()+ cancelación por timeout +scrub_secrets), con diagnóstico capturado acotado a 4 KiB. - Salidas inyectadas en la observación del tool:
\n[verify: PASS] <N> rule(s) succeeded (<cmds>)— másimpacted_tests: [...]cuando el índice Scent identifica testsscope:testalcanzables;\n[verify: FAIL] <cmd> (exit <code> | timed out after <N>s)\n<diagnóstico>\n(Fix the error before finishing the turn.);\n[verify: BLOCKED] <cmd> (denied by [permissions])— la regla no se ejecuta.
- Gobernanza
[permissions].deny: cadacommandse evalúa comoshell_execantes de ejecutarse; undenybloquea la regla ([verify: BLOCKED]) y detiene el bucle de verificación de esa edición. - Workspace Trust Gate: la fusión es
global (~/.onyx/config.toml) < workspace (<workspace>/.onyx/config.toml, confiado); un workspace no confiado ignora por completo sus[verify]/[[verify.rules]](con advertencia accionable enpolicy.trust_warnings), mientras que la configuración global sí aplica. Las reglas de workspace reemplazan al conjunto global cuando el workspace está confiado.
3. Protección Read-Only del Control Plane
Incluso en modo BUILD y con --auto-approve, onyx-workspace protege como solo lectura los archivos críticos del plano de control del agente y del repositorio:
.onyx/config.toml(evita que un agente se auto-conceda permisos o desactive el sandbox)..onyx/vault/**(evita que un agente borre o corrompa los snapshots y transcripciones de la bóveda de sesiones)..git/hooks/**y.git/config(evita inyección de código al ejecutar comandos Git)..envy.env.*(evita exfiltración o corrupción de secretos locales).
Esta protección se aplica tanto en fs_write / fs_edit como en inspecciones de escritura sobre shell_exec.
Gobernanza del delta de subagent_merge (3-way merge)
Cuando un job asíncrono (spawn_subagent / /spawn) se fusiona con subagent_merge / /merge, el delta <root>..<merged_tree> se clasifica antes de tocar disco:
Deny— Control Plane: si el delta toca.onyx/config.toml,.onyx/vault/**,.git/hooks/**,.git/configo.env*, el merge se bloquea entero (un solo archivo bloquea todo el delta; nunca se aplica parcialmente).Ask— superficies de gobernanza: si el delta tocasprout.tomlo.github/workflows/**, la aprobación del merge debe ser explícita (nunca auto-aprobada), aunque tus reglasallowcubran otras herramientas.Safe: el resto del delta sigue la aprobación estándar por impacto (Scent-Heated Approval).
La fusión es 3-way con git merge-tree sin mover HEAD ni el índice del workspace; el veredicto se aplica sobre el delta completo.
4. Sandbox OS, env_clear() y ProcessJob RAII
Toda ejecución de shell_exec (y los procesos locales de Sprout) pasa por la infraestructura compartida de onyx-workspace/src/sandbox.rs.
Perfiles de sandbox (--sandbox)
| Modo | Badge TUI | Comportamiento |
|---|---|---|
workspace-write (default) | [SANDBOX:workspace] (Linux bwrap / macOS sandbox-exec), [SANDBOX:env+job] (Windows) o [SANDBOX:env+pgid] | env_clear(), aislamiento nativo de escritura (en Linux/macOS), Win32 Job Objects / PGID, límites de memoria/PIDs y red offline por defecto. En Windows, usa strict-container para aislamiento fuerte de FS/red. |
strict-container | [SANDBOX:strict] | Ejecuta el comando dentro de un contenedor OCI (docker, nerdctl o podman) montando el workspace. Ideal para automatización desatendida. |
off | [SANDBOX:off] | Desactiva el wrapper de sandbox OS (siguen activos WorkspacePolicy, timeout, limpieza de procesos y Control Plane RO). |
Política de red (--sandbox-net)
| Política | Comportamiento |
|---|---|
offline (default) | Bloquea tráfico de red saliente y comandos de red antes de lanzar el proceso, e inyecta variables offline (CARGO_NET_OFFLINE, PIP_NO_INDEX, NPM_CONFIG_OFFLINE). |
localhost | Permite tráfico local (127.0.0.1 / localhost), útil para probar APIs o bases de datos levantadas con sprout.toml. |
unrestricted | Sin restricción de red saliente (úsalo solo cuando necesites descargar dependencias). |
Elevación automática con --auto-approve
Si pasas --auto-approve y tu configuración tenía mode = "off", openonyx eleva automáticamente el sandbox a workspace-write + offline para reducir el radio de impacto, salvo que pases explícitamente --sandbox off en la línea de comandos.
Sanitización de entorno (env_clear())
Antes de arrancar un subproceso:
- Se limpia el entorno con
env_clear()y se reconstruye solo una lista segura de variables esenciales del sistema (PATHlimpio,HOME/USERPROFILE, toolchains estándar). - Se eliminan todas las variables sensibles (
*_API_KEY,*_TOKEN,AWS_*, etc.), evitando que un comando enshell_execpueda leer tuGEMINI_API_KEYoOPENAI_API_KEY. TMP/TEMP/TMPDIRse redirigen a un directorio temporal propio de la sesión.- Además, toda la salida capturada pasa por
scrub_secretsantes de volver al modelo o grabarse en transcripciones.
Comportamiento por sistema operativo y ProcessJob RAII
- Windows (
win32-job): cada comando se envuelve en un Win32 Job Object conJOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSEy límites de memoria/PIDs. Si vence--shell-timeouto cierrasopenonyx, el árbol entero de procesos hijos muere al instante sin dejar huérfanos. - Linux (
bwrap/landlock+PGID): usa Bubblewrap (bwrap) cuando está disponible y pasa una sonda real en vivo (bwrap_is_usable()). En distribuciones como Ubuntu 24.04 donde AppArmor bloquea unprivileged user namespaces,openonyxdetecta el bloqueo automáticamente y aplica fallback seguro sin rompershell_exec, manteniendoenv_clear(), control offline, Control Plane RO y limpieza de grupos de procesos POSIX (PGID). - macOS (
sandbox-exec+PGID): utiliza perfilessandbox-execjunto conenv_clear()y limpieza por grupo de procesos POSIX.
Para comprobar qué driver nativo y qué runtime de contenedores (docker/nerdctl/podman) detecta tu máquina, ejecuta:
openonyx doctor
← 02. Interfaz TUI y Flujo Diario · Índice · Siguiente: 04. Time-Travel, Snapshots y Forking →
04. Time-Travel, Snapshots y Forking
Una de las capacidades diferenciales de openonyx es que el estado completo del agente vive en un grafo EAV determinista que puede guardarse, inspeccionarse, reproducirse sin red, revertirse en disco y bifurcarse sin destruir la rama original.
1. Bóveda de Sesiones (.onyx/vault/) y --auto-save
Para evitar ensuciar la raíz del repositorio con directorios .snaps_*, forks y archivos .tr, openonyx centraliza las sesiones en <workspace>/.onyx/vault/:
<workspace>/.onyx/vault/
├── .gitignore # creado automáticamente con `*`
├── 20261121-103500_qwen3-coder_main/ # generado por --auto-save
│ ├── snapshots.onyxpack
│ └── 20261121-103500_qwen3-coder_main.tr
├── 20261121-103500_qwen3-coder_main.fork-t12/ # rama creada por /fork o /rewind
├── feat-auth/ # --snapshot-dir feat-auth --record chat.tr
│ ├── snapshots.onyxpack
│ └── chat.tr
└── unassigned/ # solo --record suelta.tr (sin snapshot-dir)
└── suelta.tr
Reglas de resolución
--auto-save(oONYX_AUTO_SAVE=1): crea automáticamente<workspace>/.onyx/vault/<YYYYMMDD-HHMMSS>_<modelo>[_<rama|goal>]/consnapshots.onyxpacky<id>.trjuntos, muestravault:<id>en la cabecera de la TUI y al salir imprime el comando exactoopenonyx chat --resume <id>.- Nombres cortos sin separador de ruta (
/o\):--snapshot-dir feat-auth→.onyx/vault/feat-auth/--snapshot-dir feat-auth --record chat.tr→ el.trse guarda dentro de.onyx/vault/feat-auth/chat.tr.--record solo.tr(sin--snapshot-dir) → se guarda en.onyx/vault/unassigned/solo.tr.
- Rutas explícitas intactas: cualquier ruta absoluta o con separador (
./mi-dir,C:\tmp\snaps,../otro) se respeta tal cual. - Búsqueda transparente al leer:
--resume,inspect,rewind,replayydoctorbuscan primero la ruta literal en disco y, si es un nombre corto, la localizan automáticamente dentro de.onyx/vault/(y.onyx/vault/unassigned/para.tr). - Aislamiento total de Git y herramientas:
openonyxcrea.onyx/vault/.gitignore(*) automáticamente para quegit statusy los checkpoints/undonunca absorban el vault, mientrasWorkspacePolicyoculta.onyx/vault/defs_list/glob_files/code_searchy lo protege como Control Plane de solo lectura.
2. Cómo funcionan snapshots.onyxpack y los hitos
Al pasar --snapshot-dir <dir> en chat, run o replay, MilestoneSnapshotSystem captura snapshots solo en transiciones relevantes en lugar de desperdiciar disco en ticks inactivos:
init— estado inicial de la sesión.spawn— creación de agente raíz o subagente.approval:<tool>— solicitud de aprobación de herramienta mutante.tool:<tool>/tool_error:<tool>— resultado o fallo de herramienta.cmd:/agent,cmd:/undo,cmd:/rewind,cmd:/fork,cmd:/compact,cmd:/mode ...,cmd:/new— comandos slash ejecutados.settled,failed,exit— cierre de turno o salida limpia.periodic— hitos periódicos opcionales si indicas--snapshot-every <n>.
Todos los hitos se almacenan en un único contenedor append-only comprimido <dir>/snapshots.onyxpack (ONYXPK1 con compresión zlib, payload canónico ONYXAG\x01\0 y checksum FNV-1a de 64 bits):
- Tolerancia a cortes: si un crash deja un frame truncado al final del archivo,
PackSnapshotStoreignora de forma segura la cola dañada al leer y la repara automáticamente en el siguiente append. - Compatibilidad legacy: los directorios antiguos con
tick-*.binsiguen siendo legibles automáticamente eninspect,rewindy--resume. - Retención opcional: por defecto se conserva todo el historial para poder hacer time-travel a cualquier punto; puedes activar una ventana deslizante con
--max-snapshots <n>(conservainit+ últimosn - 1hitos).
3. Inspeccionar una sesión (openonyx inspect)
Sin API key y sin tocar el workspace, puedes auditar cualquier directorio de snapshots:
# Listar todos los hitos: tick, etiqueta, tamaño comprimido/raw, FNV-1a y tree_sha Git
openonyx inspect .snaps_feat --list
# Salida en JSON para automatización o depuración
openonyx inspect .snaps_feat --list --json
# Inspeccionar el último hito o un tick concreto
openonyx inspect .snaps_feat
openonyx inspect .snaps_feat --tick 24
openonyx inspect .snaps_feat --tick 24 --json
4. Deshacer cambios paso a paso (/undo)
Cada vez que fs_write o fs_edit va a modificar el disco en modo BUILD, WorkspaceToolBridge captura automáticamente un checkpoint de árbol Git ligero usando un GIT_INDEX_FILE temporal (git add -A + git write-tree):
- Nunca toca
HEADni tus commits. - Nunca altera tu staging area (
git add). - Funciona incluso en repositorios recién inicializados sin primer commit (unborn
HEAD).
Cuando escribes /undo dentro de openonyx chat:
- Se marca en el grafo el último efecto reversible como deshecho (
ws.effect.undone). - Se restaura en disco el
tree_shaexacto anterior a esa edición (restore_git_tree_checkpoint_for_targets). - Limpieza segura de archivos nuevos: si la acción deshecha fue un
fs_writeque creó un archivo nuevo no rastreado por Git,/undolo elimina limpiamente sin borrar ningún otro archivo untracked tuyo. - Se invalidan automáticamente las cachés de sesión (
fs_readyscent_outline) para que el agente vuelva a leer el contenido real del disco.
5. Bifurcar y viajar en el tiempo en vivo (dentro de la TUI)
Si iniciaste chat con --snapshot-dir <dir> (o --resume <dir>), puedes explorar alternativas sin cerrar la TUI y sin sobrescribir el historial original:
/fork [nombre] — Bifurcar desde el tick actual
/fork experimento-parser
# o sin nombre (crea <dir>.fork-t<tick>):
/fork
- Copia todos los hitos hasta el tick actual a un directorio hermano (
<dir>.fork-experimento-parsero<dir>.fork-t42). - Cambia en caliente el store activo (
SharedPackStore) a la nueva rama. - El
snapshots.onyxpackoriginal queda 100% intacto.
/rewind [tick] — Retroceder en caliente dentro de la TUI
# 1. Ver lista de hitos disponibles con tick, etiqueta y checkpoint Git
/rewind
# 2. Retroceder al tick 18 (o al hito previo más cercano <= 18)
/rewind 18
- Guardia de seguridad: si hay un agente trabajando o una petición LLM en vuelo,
/rewindrechaza ejecutarse hasta que la sesión esté en reposo para evitar estados corruptos. - No destructivo por defecto: crea automáticamente un directorio fork hermano (
<dir>.fork-t18), restaura el grafo al tick objetivo, reconcilia los efectos huérfanos en disco (restaurando checkpoints Git y limpiando archivosfs_writeposteriores al tick) e informa del resumen directamente enMemory & Trace.
6. Time-Travel y Forking desde la CLI
También puedes retomar, bifurcar o auditar desde la línea de comandos:
Reanudar en el último hito
openonyx chat --resume .snaps_feat
Reanudar desde un tick histórico creando un fork seguro
# Crea .snaps_feat.fork-t12 y abre la TUI en el tick 12 (original intacto)
openonyx chat --resume .snaps_feat --tick 12
# Especificando ruta exacta del fork:
openonyx chat --resume .snaps_feat --tick 12 --fork-dir .snaps_ruta_b
# Atajo equivalente desde el subcomando rewind:
openonyx rewind .snaps_feat 12 --interactive
openonyx rewind .snaps_feat 12 --tui --fork-dir .snaps_ruta_b
Modo destructivo opt-in (--truncate-future)
Si deliberadamente quieres recortar el snapshots.onyxpack original descartando los ticks posteriores a <tick> en lugar de crear un fork hermano, pasa --truncate-future:
openonyx chat --resume .snaps_feat --tick 12 --truncate-future
Rewind headless con previsualización (--dry-run) y replay
# 1. Previsualizar qué efectos huérfanos y checkpoints Git se revertirían (0 cambios en disco)
openonyx rewind .snaps_feat 12 --dry-run
# 2. Retroceder y reproducir determinísticamente desde una transcripción (0 llamadas HTTP)
openonyx rewind .snaps_feat 12 --transcript feat.tr
7. Transcripciones y Replay 100% Offline (ONYXTR2)
Grabando una sesión con --record <archivo.tr> (alias --save-transcript <archivo.tr>), RecordingBridge registra todas las decisiones del LLM, llamadas estructuradas (call_id), comandos slash (Tab, /mode, /undo, /compact, etc.) y metadatos de checkpoints ([checkpoint:<head>:<tree>]). Las primitivas 0-tokens del depurador temporal se sellan en la transcripción como /__onyx_det_* (shell !cmd, /read, /inject, /step, /step-llm y la cirugía /graph): el replay las reproduce bit-a-bit con 0 I/O y 0 red (no se re-ejecuta ningún comando).
# Grabar una sesión
openonyx chat --snapshot-dir .snaps_demo --record demo.tr
# Reproducirla después sin red, sin API key y sin modificar archivos en disco
openonyx replay demo.tr --snapshot-dir .snaps_replay
Esto resulta invaluable para:
- Depuración determinista: reproducir un fallo exacto del harness o de un prompt sin volver a pagar tokens.
- Auditoría: verificar qué decisiones tomó el agente en una corrida pasada.
- Regresión: reconstruir el grafo completo desde una transcripción y compararlo con
inspect --json.
8. Auditoría de Salud (openonyx doctor)
Tras un corte de energía, un error de red o antes de un rewind delicado, ejecuta:
openonyx doctor --snapshot-dir .snaps_feat --transcript feat.tr
doctor comprueba en un solo paso:
- Estado del repositorio Git y posibles artefactos residuales.
- Integridad de
snapshots.onyxpack(cabeceraONYXPK1, checksums FNV-1a, payloadsONYXAG, detección de colas truncadas) y snapshots legacytick-*.bin. - Validez de objetos
tree_shareferenciados por el ledger de efectos. - Cabecera y legibilidad de la transcripción (
ONYXTR1/ONYXTR2). - Capacidades de sandbox OS del sistema anfitrión (
bwrap/sandbox-exec/win32-job, runtime OCI). - Validación del DAG y puertos ocupados de
sprout.toml(si existe en el workspace).
9. Paridad Web: el Time Debugger en openonyx serve
La PWA embebida tiene paridad completa con el depurador temporal de la TUI (SDD-07 Fase 4A): el mismo estado de sesión alimenta ambas superficies, por lo que lo que haces desde el navegador afecta a la sesión en vivo y viceversa.
- Pill de tick: la cabecera muestra
#tick-pill(botonera aria). En vivo dicetick N; bajo freeze o con el cursor anclado en el pasado dice⏸ X/Yy abre la barra ámbar de Time Debugger automáticamente (puedes cerrarla; se vuelve a abrir sola al congelar). - Barra ámbar: estado (
⏸ TIME FROZEN · tick X / present Y/LIVE · tick Y), slider que snapea al tick disponible más cercano (rechaza ticks purgados o futuros con aviso accionable), botones ◀/▶,Freeze/Present,Step,Step 1 LLMyResume— estos tres últimos van por el túnel de comandos sellado (/step 1,/step-llm,/go), no por la API de scrub: la bifurcación se aplica en la sesión con sus gates. - API efímera:
POST /api/v1/time/scrub(JSON:action: freeze|unfreeze|return_to_present|scrub_to|scrub_delta) muta solo el estado RAM del depurador — 0 disco, 0 eventos en el bus — y responde con el snapshottime_debugactualizado. Hereda la autenticación Bearer y el guard CSRF de todo/api/v1/*(401 sin credenciales, 403 cross-site, 400 accionable para tick futuro o acción desconocida). - Prompts planos bajo freeze:
POST /api/v1/commandresponde409 Conflictcon mensaje accionable (Paused in TIME FROZEN: use /go to resume or /inject to stage memory…);/go,/graph …,/inject …,/read …,/step …,/step-llm,/timey!cmdsiguen aceptándose. - Cirugía de memorias en la UI: con el agente raíz congelado, cada memoria del root muestra
✎(editar en un diálogo →/graph edit-mem <seq> <texto>plano) y×(eliminar con confirmación →/graph drop-mem <seq>). - Preview de proyección y aviso de revert: el snapshot Web incluye
time_debugcompleto (frozen,cursor_tick,present_tick,available_ticks,pending_revert_filesdesde los efectos del grafo vivo, 0 I/O) y, con--snapshot-dir+ objetivo LLM real, elbench_hint: un comandoopenonyx bench --snapshot-dir … --tick … --models provider:modelcopiable para comparar el modelo vivo contra un benchmark determinista desde el mismo cursor (sinergia SDD-05 §9.4).
Non-goal: los efectos de Sprout y de los servidores MCP son efectos externos de proceso: el TimeFreeze (TUI o Web) no los rebobina.
← 03. Modos, Permisos y Sandbox OS · Índice · Siguiente: 05. Herramientas, Scent, Sprout y Skills →
05. Herramientas del Agente, Scent, Sprout, Skills y Automatización
Este capítulo recoge el catálogo completo de las 24 herramientas disponibles para el agente dentro de openonyx (19 base + spawn_agent + 4 asíncronas de subagentes en worktrees Git aislados), cómo aprovechar la navegación AST multilenguaje (onyx-scent 2.0), cómo orquestar procesos y contenedores locales con sprout.toml, cómo personalizar el comportamiento mediante ONYX.md / skills y cómo ejecutar tareas en modo headless (openonyx run) o en benchmark multi-modelo (openonyx bench).
1. Catálogo Completo de las 23 Herramientas
Herramientas de solo lectura y coordinación (sin aprobación)
| Herramienta | Propósito | Notas clave |
|---|---|---|
fs_read | Leer archivos UTF-8 (enteros o por rango 1-based start_line/end_line). | Límite 64 KiB. Deduplica lecturas repetidas (unchanged_since_tick) y rangos solapados ya cubiertos (covered_by:start-end). Detecta y da aviso accionable ante artefactos binarios de OnYX (ONYXTR1/2, ONYXPK1, ONYXAG). |
fs_list | Listar árbol de directorio hasta max_depth (default 3). | Omite symlinks fuera de raíz, .git, target, node_modules, *.tr, *.onyxpack. |
glob_files | Localizar rutas por patrón glob (*, **, ?, [...], {a,b}). | Orden lexicográfico determinista (o sort_by_mtime). Rechaza path traversal. |
code_search | Búsqueda de texto literal o regex en el workspace. | Soporta case_insensitive, include_glob, exclude_glob y context_lines (0..=5) con scrub_secrets. |
scent_outline | Mapa AST paginado (@TOON v1) de símbolos, visibilidad y rangos de líneas. | Soporta Rust, Python, Java, TypeScript (.ts/.tsx/.mts/.cts), JavaScript (.js/.jsx/.mjs/.cjs), Go y C/C++ (.c/.h/.cc/.cpp/.cxx/.hh/.hpp); caché incremental blake3 + caché binaria persistente .onyx/scent.idx + caché de sesión seen_outlines invalidada automáticamente tras ediciones/shell//undo; filtros public_only, exclude_tests, cursor, max_rows (1..=500). |
scent_impact | Grafo de impacto semántico (difusión térmica entera 0..=10_000 bp, 1..=6 hops). | Indica qué símbolos y archivos se ven afectados antes de refactorizar un símbolo compartido. |
scent_references | Resuelve la definición exacta de un símbolo y sus referencias cruzadas directas (callers, callees, implementers, usuarios del tipo) como tuplas @TOON v1. | target (nombre de símbolo, Type::method o file::symbol); filtros opcionales public_only, exclude_tests, paginación cursor/max_rows (1..=500). |
git_status | Ejecuta git status --short --branch de solo lectura. | Úsala en lugar de shell_exec para comprobar cambios locales. |
git_diff | Ejecuta git diff --no-color con path, staged y context_lines opcionales. | Pasa path estrictamente tras --. |
load_skill | Carga bajo demanda una guía Markdown/skill por nombre. | Busca en .onyx/skills/, skills/, ~/.onyx/skills/ y las integradas scent y rust. |
plan_update | Actualiza el checklist estructurado de progreso (pending, in_progress, completed). | Se persiste en ws.plan.text y se renderiza en el panel derecho Live Plan. |
service_status | Consulta el estado @TOON v1 de todos los servicios de sprout.toml. | Reflejado también en el panel derecho Services (Sprout). |
service_logs | Lee las últimas líneas del ring-buffer (hasta 2.000 líneas) de un servicio Sprout. | Filtrado con scrub_secrets y decodificación UTF-8 lossy. |
spawn_agent | Delega una subtarea independiente a un subagente hijo (WaitingChildren). | Techo por defecto de 32 pasos (ajustable mediante max_steps en los argumentos JSON). Con isolated: true el hijo trabaja en un worktree Git aislado (onyx/sub/agent-*) y la raíz no se toca hasta aplicar el 3-way (ver sección 1.1). |
Herramientas mutantes (requieren aprobación en BUILD; bloqueadas en PLAN/EXPLORE)
| Herramienta | Propósito | Notas clave |
|---|---|---|
fs_write | Crear o sobrescribir un archivo UTF-8. | Captura checkpoint Git previo, muestra diff en color antes de aprobar, bloqueado en Control Plane RO. |
fs_edit | Reemplazo exacto único (old_text/new_text) o multi-hunk atómico (edits: [...]). | Exige lectura previa con fs_read. Aplica fallback por líneas y re-indentado relativo en memoria antes de escribir. Captura checkpoint Git previo. |
shell_exec | Ejecutar comando de shell dentro del workspace. | Timeout configurable (--shell-timeout, default 30s), env_clear(), sandbox OS, ProcessJob RAII, scrub_secrets, límite 32 KiB e invalidación de cachés fs_read/scent_outline. |
service_start | Arranca un servicio (id) o todo el DAG (all: true) de sprout.toml. | Respeta depends_on en orden topológico y espera sondas reales (ready_port, ready_log, ready_cmd). |
service_stop | Detiene un servicio (id) o todos (all: true). | Cierre limpio con stop_cmd / ProcessJob. |
service_exec | Ejecuta un comando dentro de un contenedor activo (docker exec / nerdctl exec / podman exec). | Aplica env_clear(), timeout y scrub_secrets. |
Herramientas asíncronas de subagentes (worktrees Git aislados)
Además de spawn_agent (síncrono, misma workspace), el agente puede lanzar jobs asíncronos que corren en worktrees Git aislados (rama onyx/sub/<job_id>) sin bloquear al agente raíz:
| Herramienta | Propósito | Notas clave |
|---|---|---|
spawn_subagent | Lanza un job asíncrono en un worktree Git aislado. | goal requerido; max_steps default 32 (máx 128); driver opcional (native por defecto o id de [[external_drivers]] — un driver externo exige aprobación o allow spawn_subagent(<driver>), capítulo 03). Paralelismo limitado por --max-subagents <n> (default 3, o ONYX_MAX_SUBAGENTS). |
subagent_status | Consulta el estado de los jobs asíncronos. | job_id opcional; muestra estado, rama, archivos tocados y resumen. |
subagent_merge | Fusiona el worktree del job con la workspace raíz (3-way, Scent-Heated Merge). | git merge-tree sin mover HEAD ni el índice. Es la única de las 4 con requires_approval: true. Gobernanza del delta: Deny si toca Control Plane (bloquea el merge entero) y Ask si toca sprout.toml / .github/workflows/** (capítulo 03); driver externo fuerza Ask. |
subagent_discard | Cancela el job y elimina su worktree y rama temporal. | Si el job está en marcha, cancela el árbol de procesos del ProcessJob. |
Equivalencias slash en la TUI: /spawn [--driver <id>] <objetivo> (lanza), /subagents (lista), /merge <job_id> (fusiona) y /discard <job_id> (descarta). Los logs completos de cada job (stdout/stderr del trabajo, sellados con scrub_secrets) se guardan en .onyx/vault/subagent-logs/<job_id>.log, y la vista F2 Agents (capítulo 02) muestra los jobs [bg] con su estado y badge → <driver>.
Drivers externos: con
driver = "opencode"(o cualquier[[external_drivers]]declarado), el job se delega a un harness CLI externo que trabaja en el mismo worktree aislado; el aislamiento de proceso, el gate de Trust y la política de red se documentan en el capítulo 03 (sección 2.7).
1.1. spawn_agent(isolated: true) — hijos sincronos en worktrees aislados
Además de los jobs asíncronos anteriores, spawn_agent admite el argumento isolated: true: el hijo síncrono (el padre queda WaitingChildren) trabaja en su propio worktree Git aislado, de modo que ediciones paralelas de varios hijos nunca tocan el working tree raíz hasta el merge.
- Creación: al detectar un
spawn_agent(isolated: true)pendiente, el bridge crea perezosamente el worktreeonyx/sub/agent-<parent>-<child>-<seq>víaWorktreeManager(SDD-09) conWorkspacePolicy::for_worktreey redNativeOffline; la creación usa un checkpointcommit-treedel working tree actual, sin moverHEADni el índice de la raíz. Si el workspace no es un repo Git (o Git < 2.38), el padre recibe un error accionable pegajoso (sin tocarroot). - Finalización: cuando el hijo termina (
Done/Failed) o desaparece del grafo, el bridge lo finaliza de forma incondicional: captura el commit efímero del working tree final del hijo, evalúa el 3-way (git merge-tree, raíz intacta) y registra unIsolatedWorktreeResult(Pending/Applied/Discarded/Transferred). - Resolución: con 3-way limpio, el resultado se aplica a la raíz (o se descarta) secuencialmente; con conflictos, el worktree queda transferido a
SubagentManagery el trabajo pasa al flujo normal desubagent_status/subagent_merge/subagent_discard(misma aprobación y gobernanza que los jobsspawn_subagent). La notificación del resultado sigue la semántica de los jobs asíncronos (last_completed_proposalsy, conproactive_notifications, unIngressEvent::Command). - Limpieza: el worktree se elimina al aplicarlo/descartarlo, en
Dropdel bridge y por la poda de worktrees huérfanos enopenonyx doctor; la rama temporalonyx/sub/<job_id>se borra siempre.
Herramientas dinámicas MCP (mcp__<server>__<tool>)
Además del catálogo fijo anterior, cada servidor MCP declarado en [mcp.servers.<name>] (capítulo 03, sección 2.8) inyecta sus tools dinámicamente al LLM con el nombre mcp__<server>__<tool>:
- Descubrimiento en arranque: el handshake
initialize→tools/list(paginado, máx. 16 páginas) recupera nombre, descripción einputSchemade cada tool; los schemas se normalizan antes de declararse al proveedor (Gemini, OpenAI y Anthropic). - Siempre aprobables:
requires_approval = trueen todas las toolsmcp__*: piden aprobación interactiva enBUILD(salvoallowmás específica) y quedanDenyenPLAN/EXPLORE, igual que las mutaciones. - Aislamiento y saneado: un servidor caído no aborta la sesión y los resultados pasan por
truncate_utf8+scrub_secrets. - Replay 0-I/O: en
openonyx replaylos toolsmcp__*se reconstruyen de la propia transcripción, sin contactar con ningún servidor.
Los subagentes no reciben tools
mcp__*: solo el agente de la sesión principal ve el registro MCP (los jobs de worktree no heredan el registro).
2. Navegación AST con onyx-scent (Scent 2.0)
En lugar de leer archivos de miles de líneas completos, openonyx anima al agente a trabajar en dos fases:
scent_outline: obtiene en pocos tokens todas las funciones, structs, traits, clases, métodos, type aliases y componentes con sus números de línea exactos en formato compacto@TOON v1(paginado concursorynext_cursor). Si el agente intenta repetir exactamente el mismo outline sobre un archivo que no ha cambiado, la cachéseen_outlinesdevuelve una respuesta compacta ahorrando tokens y evitando bucles; en cuantofs_edit,fs_write,shell_execo/undomodifican el workspace, la caché se invalida automáticamente.scent_impact/scent_references+fs_read(start_line, end_line): calcula el radio de impacto (o resuelve la definición exacta y las referencias cruzadas directas de un símbolo) antes de tocar una firma pública, y lee únicamente el bloque exacto necesario.
Lenguajes soportados por
onyx-scent(Scent 2.0): 7 lenguajes — Rust (.rs), Python (.py), Java (.java), TypeScript (.ts,.tsx,.mts,.cts), JavaScript (.js,.jsx,.mjs,.cjs), Go (.go) y C/C++ (.c,.h,.cc,.cpp,.cxx,.hh,.hpp). En JS/TS se extraen además type aliases (EntityKind::TypeAlias) y componentes (EntityKind::Component: funciones PascalCase con JSX en.tsx/.jsx), yis_callableincluye ambos. En otros lenguajes el agente utilizaglob_files+code_searchv2 +fs_read.
Caché incremental binaria .onyx/scent.idx
ONYXSCI1: el índice AST del workspace se persiste en.onyx/scent.idx(máquinaONYXSCI1: magic + versión + entradas ordenadas porrel_path+ checksumblake3final) junto con un.onyx/.gitignorede higiene que ignorascent.idxyscent.idx.tmp*; cualquier anomalía (truncado, magic/versión distinta, checksum inválido) se ignora silenciosamente y el índice se reconstruye limpio.- Excluido de los artefactos Git: los checkpoints efímeros de subagentes (
commit-tree) y la evaluación de impacto de un worktree excluyen.onyx/scent.idx*y su.gitignore, para que el trabajo del hijo no se contamine con artefactos operativos de OnYX. - Recarga incremental: en cada refresco se re-analizan únicamente los archivos cuyo mtime/contenido cambiaron (verificación por hash), de modo que repos de miles de archivos se actualizan en decenas de milisegundos; el archivo se escribe atómicamente (
scent.idx.tmp.*→ rename). - CLI
scent: el crateonyx-scent(featurecli) expone el binarioscentcon los subcomandosoutline,impactyreferences(misma salida@TOON v1que las tools del agente, para uso directo en scripts/CI).
3. Orquestación Local de Procesos y Contenedores (sprout.toml)
Si tu proyecto necesita arrancar servicios locales (bases de datos en Docker/Rancher, APIs, workers, frontends) durante una sesión de desarrollo o testing, crea un archivo sprout.toml en la raíz del workspace.
onyx-workspace incluye un supervisor puro en std (0 tokio) que valida el grafo de dependencias (DAG sin ciclos), arranca servicios en orden topológico, comprueba sondas de disponibilidad reales y cierra todos los procesos limpiamente al salir de openonyx (ProcessJob RAII).
Formato moderno ([runtime] + [services.<id>])
[runtime]
# Opcional: "docker" | "nerdctl" | "podman" (si se omite, se autodetecta)
container_cli = "docker"
[services.db]
name = "Postgres local"
kind = "container"
cmd = "docker compose up -d postgres"
stop_cmd = "docker compose stop postgres"
logs_cmd = "docker compose logs --tail=100 postgres"
container = "myapp-postgres"
# Opcional: fuerza usuario en `service_exec` (ej. "1000:1000" o "app")
# exec_user = "1000:1000"
ready_port = 5432
[services.api]
name = "API Backend"
kind = "process"
cwd = "backend"
cmd = "cargo run --bin api"
depends_on = ["db"]
ready_port = 8080
ready_log = "Listening on 127.0.0.1:8080"
También se admite el formato clásico de Sprout ([global] + [[service]] con env_wrapper, dir, debug_port, depends_on, optional, enabled).
Control interactivo desde la TUI
/services: imprime enMemory & Tracela tabla@TOON v1con estado de cada servicio./service start <id|all>: arranca un servicio (y sus dependencias) o todo el stack./service stop <id|all>: detiene un servicio o todos./service logs <id> [tail]: muestra las últimas[tail]líneas del buffer de logs.- Además, con terminal
>= 100columnas verás el estado en tiempo real en el panel derechoServices (Sprout), yopenonyx doctorvalidará tusprout.toml(sintaxis, ciclos en DAG, runtime de contenedores y puertos ya ocupados).
Nota sobre red, confianza y contenedores: si el agente necesita consultar con
shell_execuna API local levantada por Sprout (p. ej.http://127.0.0.1:8080/health), ejecutaopenonyxcon--sandbox-net localhost(o configúralo en.onyx/config.toml). Además, si el repositorio no está en tu almacén de Workspace Trust (openonyx trust addo/trust), Sprout muestra[UNTRUSTED — run /trust]y bloqueastart,stopyexechasta que confíes en elsprout.tomlactual (cualquier cambio de 1 byte revoca la confianza automáticamente).container_clisolo admitedocker,nerdctlopodman, y el campo opcionalexec_userpermite ejecutarservice_execcon un usuario concreto.
4. Instrucciones de Proyecto (ONYX.md / AGENTS.md)
En cada inicio (chat, run y rewind vivo), openonyx carga automáticamente instrucciones Markdown en este orden (hasta 16 KiB totales, siempre pasadas por scrub_secrets):
~/.onyx/AGENTS.mdy~/.onyx/ONYX.md(reglas globales personales)<workspace>/AGENTS.mdy<workspace>/ONYX.md(reglas del repositorio)
Además, inyecta automáticamente una pista del sistema operativo anfitrión (Windows PowerShell vs Unix/POSIX) para evitar comandos incompatibles en shell_exec.
Ejemplo útil de <workspace>/ONYX.md:
# Convenciones del proyecto
- Ejecuta siempre `cargo test --workspace` tras editar código Rust.
- No modifiques archivos generados bajo `dist/`.
- Escribe los mensajes de error orientados al usuario en español.
5. Crear tus Propias Skills (SKILL.md)
En lugar de inflar ONYX.md con manuales largos que se envían en cada turno, crea skills bajo demanda. Al arrancar, openonyx solo inyecta un catálogo compacto (discover_skills_summary), y el agente carga el texto completo con load_skill("<nombre>") únicamente cuando lo necesita.
Orden de búsqueda de skills
<workspace>/.onyx/skills/<nombre>/SKILL.md(recomendado por proyecto) o<nombre>.md<workspace>/skills/<nombre>/SKILL.mdo<nombre>.md~/.onyx/skills/<nombre>/SKILL.mdo<nombre>.md(globales de usuario)- Skills integradas:
scentyrust
Plantilla de una skill personalizada
Crea .onyx/skills/deploy-checks/SKILL.md:
---
name: deploy-checks
description: Checklist de verificación previa a despliegue y migraciones SQL seguras.
---
# Verificación Pre-Despliegue
1. Comprueba con `git_diff` que no haya migraciones destructivas sin plan de rollback.
2. Verifica que `cargo clippy --workspace --all-targets -- -D warnings` pase sin avisos.
3. Revisa que no queden claves ni URLs de staging en archivos de configuración.
Buenas prácticas:
- Incluye
name:ydescription:en las primeras 20 líneas (el catálogo usadescription:). - Nunca escribas secretos reales (todo pasa por
scrub_secrets). - Mantén cada skill muy por debajo de
64 KiB.
6. Automatización Headless y CI (openonyx run)
Para ejecutar una tarea única sin interfaz TUI:
# Auditoría de solo lectura sin coste humano
openonyx run "revisa git_diff y enumera posibles regresiones de seguridad" \
--effort medium \
--max-steps 32 \
--record ci_review.tr \
--snapshot-dir .snaps_ci
# Ejecución automatizada acotada con sandbox estricto
openonyx run "corrige los avisos de clippy y valida con cargo test" \
--auto-approve \
--sandbox workspace-write \
--sandbox-net offline \
--shell-timeout 120 \
--record ci_fix.tr \
--snapshot-dir .snaps_fix
Recuerda que incluso con --auto-approve, cualquier regla [permissions].deny de .onyx/config.toml y la protección RO del Control Plane siguen bloqueando acciones prohibidas.
← 04. Time-Travel, Snapshots y Forking · Índice · Siguiente: 06. Referencia CLI y Troubleshooting →
06. Referencia CLI Completa y Solución de Problemas
Referencia rápida de todos los subcomandos, flags, variables de entorno, resiliencia HTTP/SSE y soluciones a incidencias reales en Windows, Linux y macOS.
1. Referencia de Subcomandos
openonyx chat [OPCIONES] [--resume <dir> [--tick <n>] [--fork-dir <dir>] [--truncate-future]]
openonyx run <goal> [OPCIONES]
openonyx replay <transcript> [--workspace <dir>] [--snapshot-dir <dir>] [--snapshot-every <n>] [--max-snapshots <n>]
openonyx inspect <snapshot_dir> [--tick <n>] [--list] [--json]
openonyx rewind <snapshot_dir> <tick> [--transcript <file>] [--interactive | --tui] [--fork-dir <dir>] [--truncate-future] [--dry-run] [OPCIONES]
openonyx bench --snapshot-dir <dir> --tick <n> --models <list> [--goal <text>] [--verify <cmd>] [--out <file.json>] [--max-steps <n>] [OPCIONES]
openonyx doctor [--workspace <dir>] [--snapshot-dir <dir>] [--transcript <file>]
openonyx trust [--workspace <dir>] [add | list | check | revoke] [--list | --check | --revoke]
openonyx serve [--workspace <dir>] [--bind <ip:port>] [--api-key <key>] [--cors-origin <origin>] [OPCIONES]
openonyx [--help | -h | --version | -V]
2. Tabla Completa de Opciones (Flags)
| Flag | Aplica a | Descripción / Default |
|---|---|---|
-w, --workspace <dir> | Todos | Directorio del proyecto objetivo (default: directorio actual). |
--provider <gemini|openai|anthropic> | chat, run, rewind | Backend LLM (gemini por defecto; openai para OpenAI/OpenRouter/Ollama/vLLM/LM Studio; anthropic para la Messages API nativa). |
--model <name> | chat, run, rewind | Nombre del modelo (defaults: gemini-4-hydrogen en Gemini, gpt-4o en OpenAI, claude-sonnet-4-5 en Anthropic). |
--effort <low|medium|high> | chat, run, rewind | Esfuerzo de razonamiento/pensamiento (thinkingLevel / reasoning_effort; en anthropic mapea al presupuesto de thinking 2048/8192/16384 salvo presupuesto explícito). |
--thinking-budget <n> | chat, run, rewind | Presupuesto de extended thinking de Anthropic en tokens (0 = off, o 1024..=60000; o ANTHROPIC_THINKING_BUDGET). Eleva max_tokens por encima del presupuesto. |
--api-base <url> | chat, run, rewind | URL base personalizada (http:// permitido solo en loopback localhost/127.0.0.1/[::1]; hosts remotos exigen https://). |
--allow-custom-auth-host | chat, run, rewind | Opt-in explícito para enviar API keys a hosts HTTPS remotos no oficiales (o ONYX_ALLOW_CUSTOM_AUTH_HOST=1). |
--trust-workspace | chat, run, rewind, serve | Confía el workspace actual en memoria durante la sesión (sin modificar ~/.onyx/trusted_workspaces.toml). |
--bind <ip:port> | serve | Dirección HTTP/SSE (default: 127.0.0.1:8787; direcciones no loopback exigen --api-key explícita >= 16 chars). |
--api-key <key> | serve | API key para autenticación (cookie HttpOnly o Authorization: Bearer; en loopback se genera aleatoria si se omite). |
--cors-origin <url> | serve | Origen explícito permitido para frontales externos (p. ej. SPA Svelte en http://localhost:5173; nunca *). |
--sandbox <off|workspace-write|strict-container> | chat, run, rewind | Perfil de sandbox OS para shell_exec (default: workspace-write). |
--sandbox-net <offline|localhost|unrestricted> | chat, run, rewind | Política de red del sandbox (default: offline). |
--auto-approve | chat, run, rewind | Omite confirmaciones interactivas para herramientas mutantes (deny sigue aplicando y eleva sandbox off → workspace-write + offline salvo --sandbox off). |
--ignore-deny | chat, run, rewind | Desactiva explícitamente las reglas [permissions].deny de .onyx/config.toml. |
--max-steps <n> | chat, run | Límite de pasos por turno del agente raíz (default: 128 en chat, 64 en run; subagentes 32 por defecto). |
--max-subagents <n> | chat, run, serve, rewind --interactive | Máximo de worktrees Git en paralelo para subagentes asíncronos (default: 3, o ONYX_MAX_SUBAGENTS). |
--shell-timeout <secs> | chat, run | Timeout en segundos por comando shell_exec (default: 30s). |
--auto-save | chat, run | Crea automáticamente .onyx/vault/<YYYYMMDD-HHMMSS>_<modelo>[_<rama|goal>]/ con snapshots.onyxpack + .tr juntos (o ONYX_AUTO_SAVE=1). |
--record <f>, --save-transcript <f> | chat, run | Guarda transcripción determinista ONYXTR2 (nombres cortos van dentro de --snapshot-dir, o en .onyx/vault/unassigned/ si no hay snapshot dir). |
--snapshot-dir <dir> | chat, run, replay, doctor | Directorio para snapshots.onyxpack (nombres cortos se resuelven en .onyx/vault/<dir>/). |
--snapshot-every <n> | chat, run, replay | Captura además un hito periodic cada <n> ticks. |
--max-snapshots <n> | chat, run, replay | Retención opt-in por ventana deslizante (init + últimos n - 1 hitos). |
-r, --resume <dir> | chat | Reanuda desde el último hito (o --tick <n>) guardado en <dir>. |
--tick <n> | inspect, chat --resume | Tick específico a inspeccionar o desde el que reanudar/bifurcar. |
--fork-dir <dir> | chat --resume --tick, rewind --interactive | Directorio destino del fork de snapshots. |
--truncate-future | chat --resume --tick, rewind | Opt-in destructivo: trunca el pack origen in-place en lugar de crear un fork hermano. |
--interactive, --tui | rewind | Abre la TUI interactiva en el tick restaurado en lugar de continuar en headless. |
-l, --list | inspect | Lista todos los hitos con etiquetas, tamaños, FNV-1a y checkpoints Git. |
--json | inspect | Emite salida estructurada en JSON. |
--transcript <file> | rewind, doctor | Reproduce transcripción desde el punto de rewind o valida su cabecera en doctor. |
--dry-run | rewind | Previsualiza efectos huérfanos y plan de rollback sin modificar disco. |
--models <list> | bench | Lista de candidatos separada por comas: <provider>:<model> (LLM vivo, p. ej. gemini:gemini-2.5-pro,openai:gpt-4o) y/o replay:<label>=<file.tr> / replay:<file.tr> (transcripción ONYXTR2 offline, determinista). |
--verify <cmd> | bench | Comando de verificación ejecutado sandboxed dentro del worktree del candidato tras asentarse (misma tubería de shell_exec); su exit 0 decide passed_verify. Sin --verify, passed_verify = el agente terminó Done y la sesión se asentó. |
--out <file.json> | bench | Escribe el informe JSON completo (metadata + resultados) en pretty-print. |
--goal <text> | bench | Objetivo del agente raíz si en el --tick no hay agente activo (obligatorio en ese caso). |
-h, --help / -V, --version | Global | Muestra ayuda o versión y sale con código 0. |
openonyx bench — referencia completa
Benchmark multi-modelo desde un snapshot idéntico: cada candidato se ejecuta en un worktree desechable (bench-<pid>-<idx>-<label>) con rewind a --tick (reconcile_rewind_effects_report), un host de sesión fresco (request_restore + 1 step) y, al terminar, la raíz y HEAD quedan 100 % intactos y el worktree se elimina (guard RAII; también en error o pánico).
# Comparativa en vivo + replay offline, con verificación y informe JSON
openonyx bench \
--snapshot-dir .onyx/vault/20261125-100000_gpt-4o \
--tick 12 \
--models "gemini:gemini-2.5-pro,openai:gpt-4o,replay:baseline=run_baseline.tr" \
--goal "fix the failing test in src/app.rs" \
--verify "cargo test --workspace" \
--out bench_report.json \
--auto-approve \
--sandbox workspace-write \
--sandbox-net offline
- Candidatos (
--models):<provider>:<model>conprovider ∈ gemini|openai|anthropic(credenciales vía las variables habitualesGEMINI_API_KEY/OPENAI_API_KEY/ANTHROPIC_API_KEYo--api-base);replay:<label>=<path.tr>fija el label;replay:<path.tr>usa el file stem como label. El parse divide primero por:y luego por=, de modo que las rutas con letra de unidad Windows (replay:C:\runs\a.tr) se conservan intactas. - Ejecución por candidato (secuencial): rewind del worktree al tick → host fresco restaurado → si no hay agente activo en el tick, se spawnea un agente raíz con
--goal→ se ejecuta hasta asentarse (tope interno de 256 ticks) con telemetría real (tokens/coste) en candidatos vivos (replay: tokens/coste0). --auto-approve: para ejecución desatendida en worktrees desechables: cada candidato corre solo en su worktree, la raíz nunca se toca;[permissions].denysigue aplicando.- Salida: tabla Markdown de 9 columnas en
stdout—| model | passed_verify | ticks | tool_calls | input_tokens | cached_tokens | output_tokens | estimated_cost_usd | wall_time_ms |— y, con--out, el informe JSON (metadatacon snapshot/tick/models/verify +resultspor candidato con todas las columnas). - Flags reutilizados:
--workspace <dir>,--sandbox <off|workspace-write|strict-container>,--sandbox-net <offline|localhost|unrestricted>,--shell-timeout <secs>,--trust-workspace,--api-base <url>,--allow-custom-auth-host,--effort <low|medium|high>,--thinking-budget <n>(el candidato vivo determina su propioprovider:model). - Validación accionable: sin
--snapshot-dir/--tick/--modelsel error indica la flag que falta; proveedor desconocido →unsupported provider ... (expectedgemini,openaioranthropic); snapshot ausente → aviso de suelo (floor), no error.
3. Variables de Entorno
| Variable | Proveedor | Descripción |
|---|---|---|
ONYX_PROVIDER | Todos | Proveedor por defecto (gemini | openai | anthropic). |
GEMINI_API_KEY | Gemini | API key de Google AI Studio (fallback: ONYX_API_KEY). |
OPENAI_API_KEY | OpenAI | API key para --provider openai (fallback: ONYX_API_KEY; opcional con --api-base local). |
ANTHROPIC_API_KEY | Anthropic | API key para --provider anthropic (fallback: ONYX_API_KEY). |
ONYX_API_KEY | Todos | Clave compartida de fallback si no se define la específica del proveedor. |
ONYX_MODEL | Todos | Modelo por defecto (fallbacks: ONYX_GEMINI_MODEL para Gemini, OPENAI_MODEL para OpenAI, ANTHROPIC_MODEL para Anthropic). |
ONYX_EFFORT | Todos | Esfuerzo por defecto (low | medium | high; fallbacks: GEMINI_THINKING_LEVEL, OPENAI_REASONING_EFFORT; en Anthropic lo gobierna ANTHROPIC_THINKING_BUDGET). |
ONYX_AUTO_SAVE | Ambos | Activa --auto-save por defecto (1 | true | yes | on) guardando en .onyx/vault/. |
ONYX_MAX_SUBAGENTS | Ambos | Máximo de worktrees en paralelo para subagentes asíncronos (usado cuando no se pasa --max-subagents <n>; default: 3). |
GEMINI_API_BASE | Gemini | Endpoint personalizado para Gemini. |
OPENAI_API_BASE / OPENAI_BASE_URL | OpenAI | Endpoint compatible con OpenAI (default: https://api.openai.com/v1). |
ANTHROPIC_API_BASE | Anthropic | Endpoint personalizado de la API de Anthropic (default: https://api.anthropic.com). |
ANTHROPIC_THINKING_BUDGET | Anthropic | Presupuesto de extended thinking en tokens (0 = off, o 1024..=60000); tiene prioridad sobre el presupuesto derivado de --effort. |
Configuración LLM, drivers y MCP en
config.toml: además de flags y variables,.onyx/config.tomlacepta bloques[[llm_profiles]](capítulo 03, sección 2.6),[[external_drivers]](capítulo 03, sección 2.7) y[mcp.servers.<name>](capítulo 03, sección 2.8). Las credenciales de un perfil se resuelven en el ordenapi_key_env→ variable estándar del proveedor →ONYX_API_KEY.
4. Resiliencia HTTP/SSE en Endpoints OpenAI, vLLM y Proxies
En servidores locales o proxies corporativos (vLLM, LiteLLM, nginx, Cloudflare) es frecuente que la conexión chunked SSE se cierre bruscamente tras emitir finish_reason o que devuelva un error transitorio (408, 429, 500, 502, 503, 504 o corte temporal de red).
El adaptador open-onyx/src/openai.rs incorpora dos protecciones automáticas:
- Tolerancia a EOF tras respuesta completada: si el stream SSE falla al decodificar el último chunk pero ya se recibió
finish_reason/[DONE]con respuesta otool_callscompletos, la respuesta se acepta sin abortar el turno. - Reintentos automáticos con backoff: ante fallos HTTP o de transporte transitorios, reintenta automáticamente hasta 2 veces (
400ms,1200ms) antes de reportar error al agente.
El adaptador nativo open-onyx/src/anthropic.rs aplica la misma política de reintentos (408, 429, 500, 502, 503, 504 y el overloaded_error 529 propio de Anthropic), respetando el header retry-after cuando el servidor lo envía.
5. Solución de Problemas Frecuentes (Troubleshooting)
1. GEMINI_API_KEY environment variable is not set
- Si quieres usar Gemini: exporta
GEMINI_API_KEY(PowerShell:$env:GEMINI_API_KEY="..."; bash/zsh:export GEMINI_API_KEY="..."). - Si quieres usar Ollama / vLLM / LM Studio: añade
--provider openai --api-base http://localhost:11434/v1 --model <tu-modelo>(así no se exige API key). - Si solo quieres usar
inspect,replay,rewind --dry-runodoctor: ninguno de ellos requiere API key.
2. El agente intenta leer un .tr, .onyxpack o tick-*.bin con fs_read
fs_read detecta automáticamente las cabeceras binarias de OnYX (ONYXTR1, ONYXTR2, ONYXPK1, ONYXAG) y devuelve un error explicativo recomendando usar openonyx inspect o openonyx replay en lugar de leer el binario como texto.
3. shell_exec falla con error de red (offline) al ejecutar cargo build o curl
Por defecto el sandbox usa --sandbox-net offline (inyectando además CARGO_NET_OFFLINE=true).
- Si necesitas consultar un servicio local de Sprout (
127.0.0.1): usa--sandbox-net localhost. - Si necesitas descargar crates o paquetes de internet: usa
--sandbox-net unrestricted(o añádelo temporalmente en.onyx/config.toml).
4. Linux Ubuntu 24.04+: bwrap no puede crear user namespaces (AppArmor)
Ubuntu 24.04 restringe unprivileged user namespaces vía AppArmor. openonyx ejecuta una sonda real (bwrap_is_usable()) y aplica automáticamente un fallback seguro para que shell_exec no falle. Comprueba el estado exacto en openonyx doctor.
5. Ctrl+Tab no cambia de agente en mi terminal
Algunos emuladores de terminal (especialmente en Windows o a través de tmux/SSH) interceptan o no envían Ctrl+Tab. Usa siempre la tecla F2 (ahora abre la vista Agents, capítulo 02) o el comando /agent [id|name], que funcionan en el 100% de terminales.
6. /rewind dice que no puede ejecutarse mientras hay actividad
Por seguridad, /rewind <tick> en vivo requiere que ningún agente esté thinking, acting, waiting_children ni con una llamada LLM en vuelo. Espera a que el turno termine (emblema detenido / Settled), o sal con Esc y ejecuta openonyx chat --resume <dir> --tick <n>.
7. Windows PowerShell: comillas o redirecciones en shell_exec
openonyx informa al modelo del sistema operativo anfitrión (Windows PowerShell vs Unix/POSIX), pero si un modelo local insiste en usar sintaxis bash (&&, grep, cat), recuérdale en tu ONYX.md del proyecto que use herramientas nativas (code_search, glob_files, fs_read, git_diff) y comandos compatibles con PowerShell.
8. Corte inesperado durante una sesión larga
- Ejecuta
openonyx doctor --snapshot-dir <dir>para comprobar si quedó una cola truncada ensnapshots.onyxpack. - Revisa los hitos intactos con
openonyx inspect <dir> --list. - Reanuda con
openonyx chat --resume <dir>(la cola truncada se ignora de forma segura al leer y se repara automáticamente al guardar el próximo hito).
9. openonyx doctor avisa o falla en un driver externo ([[external_drivers]])
doctor audita las declaraciones de [[external_drivers]] (capítulo 03, sección 2.7):
- Preset integrado
opencode:[WARN]si el binarioopencodeno está enPATH(el preset se omite). - Driver declarado cuyo
binno existe:[ERR]—/spawn --driver <id> will fail at runtime. binencontrado pero la sonda--version(deadline 3 s, entorno saneado) se queda a tiempo:[ERR]; si responde con error (p. ej., flags mal puestas):[WARN].prompt_transport = "arg"en Windows:[WARN]si el binario resuelve a un wrapper.cmd/.bat(rechazado en el spawn).network_allowlistsin--sandbox strict-container:[WARN]— la allowlist es advisory fuera destrict-container; un driver declarado sinnetwork_allowlistquedaLocalhostOnlysalvo que el sandbox lo relaje.
10. Un servidor MCP no se conecta o [mcp.servers.*] queda ignorado
openonyx doctor audita los servidores declarados en [mcp.servers.<name>] (capítulo 03, sección 2.8) con un handshake acotado a 5 s (un servidor caído nunca colga doctor):
ConnectedoDisabled:[CHECK]informativo.Failed(...)(binario ausente, timeout del handshake, error del servidor):[ERR]accionable con el mensaje ya scrubbeado; la sesión sigue funcionando sin ese servidor (aislamiento de fallos).- Workspace no confiado con
[mcp.servers.*]de proyecto:[WARN]MCP config in ... ignored: workspace is not trusted (use --trust-workspace or openonyx trust)— aprueba conopenonyx trusto usa--trust-workspace. - Tools
mcp__*siempre piden aprobación enBUILDy quedanDenyenPLAN/EXPLORE; si quieres auto-aprobarlas, declaraallow = ["mcp__<server>__*"]en.onyx/config.toml(workspace confiado).
11. La Web (o la TUI) no acepta mi prompt: 409 Conflict / "Paused in TIME FROZEN"
Es el guard de TimeFreeze (capítulo 04, sección 9): la sesión está congelada (breakpoint temporal activo) y un prompt plano desordenado rompería la bit-a-bit del replay. No es un fallo — son las vías de escape:
/go(o/unfreeze): bifurca si el cursor mira el pasado y reanuda en el presente./inject <texto>//graph …//read …//step [n]//step-llm/! <cmd>: siguen funcionando bajo freeze (primitivas 0-tokens selladas).- En la Web, la barra ámbar (pulsar
#tick-pill) tieneResume; en la TUI,Escvuelve al presente sin salir yCtrl+Talterna el freeze. - En
POST /api/v1/commandel 409 incluye el mensaje accionable completo; un400enPOST /api/v1/time/scrubsignifica tick futuro/purgado o acción desconocida (el body lo explica).
← 05. Herramientas, Scent, Sprout y Skills · Volver al Índice del Manual
openOnyx (openonyx) User Manual
Welcome to the official manual for openonyx, the deterministic coding-agent CLI, TUI, and embedded Web PWA harness built on the OnYX microkernel (onyx-core → onyx-soul-agents → onyx-workspace → open-onyx).
Unlike conventional terminal coding assistants backed by mutable message arrays, openonyx records every decision, read, edit, and command inside a deterministic EAV graph featuring:
- Compressed milestone snapshots (
snapshots.onyxpack) with 64-bit FNV-1a checksums and truncated-tail crash tolerance. - Centralized session vault (
.onyx/vault/+--auto-save) auto-ignored by Git so workspace roots stay clean. - Non-destructive time-travel & forking (
/rewind,/fork,chat --resume --tick,rewind --interactive). - Interactive Time Debugger (
TimeFreeze, SDD-07): pause the session at any tick (TUI:Alt+←/→,Ctrl+T,/time,/go,/step,/step-llm; Web:#tick-pill→ amber bar) over a RAM tick-boundary ring + on-disk milestones; 0-token primitives sealed intoONYXTR2(0 network, 0 disk:!cmd,/read,/inject,/step) and safe surgery on the frozen graph with/graph(inspect/drop-mem/edit-mem/set-goal); 100 % ephemeral until the branch is confirmed. - Asynchronous subagents in isolated Git worktrees (
spawn_subagent//spawn, 3-way merge with Scent-Heated Merge,--max-subagents, and optional external CLI harness drivers via[[external_drivers]]), plusspawn_agent(isolated: true): synchronous children in isolatedonyx/sub/agent-*worktrees with 3-way reconciliation that never touchesHEADor the root until merged. - Multi-model benchmarking (
openonyx bench): identical snapshot/tick, throwaway per-candidate worktrees (rewind + RAII), liveprovider:modelor offlinereplay:<label>=<file.tr>candidates, sandboxed--verify, 9-column Markdown table + JSON report via--out; the root stays 100 % intact. - Verify-on-Edit (
[verify]/[[verify.rules]]in.onyx/config.toml): after each successfulfs_edit/fs_write, runs the rules whoseglobmatches the edited file (plus Scent-impactedscope:testfiles) in the sandbox and injects[verify: PASS|FAIL|BLOCKED]into the tool observation, subject to Workspace Trust and[permissions].deny. - Hot-swappable LLM targets (
[[llm_profiles]],/profile//provider//model//effort, liveprovider/modelheader and credential-free Web selector), including a native Anthropic provider (Messages API, ephemeral prompt caching, and budgeted extended thinking via--thinking-budget). - Dynamic MCP tools (
[mcp.servers.<name>],stdioandhttptransports): each tool is exposed asmcp__<server>__<tool>, always approval-gated,DenyinPLAN/EXPLORE, behind the Workspace Trust gate, with per-server failure isolation andopenonyx doctorauditing. - Modular
F1..F5TUI views (Chat, Agents, Sprout, Plan & Diff, Timeline) with aCtrl+Kcommand palette and/view. - Transactional Git checkpoints (
/undo) without mutatingHEADor your staging index. - 100% offline deterministic replay (
ONYXTR2, 0 network calls, 0 disk writes). - Defense-in-depth security:
blake3Workspace Trust (openonyx trust//trust),PLAN/BUILD/EXPLOREmodes,.onyx/config.tomlrules (deny > ask > allow), Scent-Heated Approvals, OS sandboxing withenv_clear(), Control Plane RO protection, and RAIIProcessJobprocess-tree teardown. - Embedded Web UI / PWA (
openonyx serve): pure-stdHTTP/1.1 + SSE server (0tokio) ready for desktop browsers, mobile phones, or HTTPS reverse proxies, withblake3constant-time auth (HttpOnlycookie /Bearer) and explicit--cors-originsupport for external frontends. - Semantic AST navigation, Scent 2.0 (
onyx-scent:scent_outline+scent_impact+scent_references): 7 languages (Rust, Python, Java, TypeScript, JavaScript, Go, C/C++),EntityKind::{TypeAlias, Component}kinds, incremental binary cache.onyx/scent.idx(ONYXSCI1, sub-20 ms reloads) and thescent outline|impact|referencesCLI; plus local process/container orchestration (sprout.toml).
Table of Contents
| Chapter | Topics |
|---|---|
| 01. First Steps (Quickstart) | Build/install, configure Gemini / OpenAI / Ollama / vLLM, --auto-save, first interactive TUI session to Settled, diff approvals, Tab Plan/Build, and /undo. |
| 02. TUI & Daily Workflow | Compact 3-row header with live provider/model, Braille emblem, --effort, live vault:<session> badge, live telemetry, Memory & Trace scroll, Live Plan & Services (Sprout) panels, tiered context + /compact [focus], /new, modular F1..F5 views + Ctrl+K palette + /view, multi-agent supervision (spawn_agent, /agent, Ctrl+Tab), and hot-swapping the LLM target (/profile, /provider, /model, /effort). |
| 03. Modes, Permissions & OS Sandbox | PLAN, BUILD, and EXPLORE modes; declarative .onyx/config.toml ([permissions], [sandbox], and [verify] Verify-on-Edit), deny > ask > allow, --ignore-deny, --auto-approve elevation, MCP servers ([mcp.servers.<name>], mcp__<server>__<tool>, approval gate, Deny in PLAN/EXPLORE), Control Plane RO protection, env_clear(), RAII ProcessJob, and Linux (bwrap + AppArmor fallback) / macOS / Windows drivers. |
| 04. Time-Travel, Snapshots & Forking | Session vault (.onyx/vault/ & --auto-save), snapshots.onyxpack, automatic milestone tags, /undo (including untracked fs_write cleanup), live /rewind [tick] & /fork [name], chat --resume --tick, rewind --interactive, offline replay (ONYXTR2), inspect, and doctor. |
| 05. Tools, Scent, Sprout & Skills | Full 24-tool reference (including the async subagent tools spawn_subagent / subagent_status / subagent_merge / subagent_discard, spawn_agent(isolated: true) isolated worktrees, and external CLI harness drivers) plus dynamic mcp__* tools, Scent 2.0 AST navigation (7 languages, scent_outline + scent_impact + scent_references, .onyx/scent.idx ONYXSCI1 cache, scent CLI), local service & container orchestration (sprout.toml, /services, /service), project instructions (ONYX.md/AGENTS.md), authoring custom skills, and headless automation (openonyx run). |
| 06. CLI Reference & Troubleshooting | Complete subcommand, flag, and environment-variable tables (including --thinking-budget, ANTHROPIC_*, and the full openonyx bench reference: --models live/replay candidates, --verify, --out, --goal), OpenAI/vLLM and Anthropic SSE EOF resilience & retries, openonyx doctor checklist (with MCP server audit), and practical Windows/Linux/macOS troubleshooting. |
Recommended Reading Paths
- First day with
openonyx: start with 01. First Steps, then read 02. TUI & Daily Workflow. - Running local LLMs (Ollama, vLLM, LM Studio): see local provider setup in 01. First Steps,
--effortin 02. TUI & Daily Workflow, and SSE retry resilience in 06. CLI Reference & Troubleshooting. - Strict security / corporate environments: read 03. Modes, Permissions & OS Sandbox.
- Branching experiments & reproducible audits: read 04. Time-Travel, Snapshots & Forking.
- Local microservices & containers: see Sprout in 05. Tools, Scent, Sprout & Skills.
Prerequisites
- Rust
1.85or newer (the repository pins1.85.1inrust-toolchain.tomlwithedition = "2024"). - Git on
PATH(required for reversible/undocheckpoints,rewind,git_status, andgit_diff). - Access to an LLM:
- A Google AI Studio (
GEMINI_API_KEY) key, or - An OpenAI / OpenRouter (
OPENAI_API_KEY) key, or - An Anthropic (
ANTHROPIC_API_KEY) key for the native provider (--provider anthropic), or - Any local OpenAI-compatible
/v1/chat/completionsserver such as Ollama, vLLM, or LM Studio (no API key required).
- A Google AI Studio (
- Optional:
docker,nerdctl, orpodmanfor--sandbox strict-containerorkind = "container"services insprout.toml;bwrap(Bubblewrap) on Linux for filesystem sandboxing.
Other Repository Documentation
- Repository README (EN) · README en Español
open-onyxTechnical READMEonyx-workspaceTechnical README- Agent Operational Skill (
SKILL.md) - Changelog (
CHANGELOG.md)
01. First Steps with openOnyx (Quickstart)
Go from building openonyx to completing your first supervised coding session — with live SSE streaming, colorized diff approvals, PLAN/BUILD mode toggling, and transactional Git /undo — in under 10 minutes.
1. Build or Install openonyx
From the OnYX repository root:
# Optimized build (recommended for daily use)
cargo build --release -p open-onyx
# Or install into ~/.cargo/bin so `openonyx` is available in any project
cargo install --path open-onyx
Verify the binary and audit your local environment:
openonyx --version
openonyx --help
openonyx doctor
Tip: If you did not install globally, replace
openonyxwithcargo run --release -p open-onyx --or./target/release/openonyx(Windows:.\target\release\openonyx.exe).
2. Configure an LLM Provider
openonyx natively supports Google Gemini (default) and any OpenAI-compatible /v1/chat/completions endpoint (OpenAI, OpenRouter, Ollama, vLLM, LM Studio).
Option A — Google Gemini (default)
Windows (PowerShell):
$env:GEMINI_API_KEY = "your-api-key"
openonyx chat --auto-save
Linux / macOS (bash/zsh):
export GEMINI_API_KEY="your-api-key"
openonyx chat --auto-save
To pick a specific model or reasoning effort (low, medium, high):
openonyx chat --model gemini-2.5-pro --effort high --auto-save
Option B — OpenAI / OpenRouter
Windows (PowerShell):
$env:OPENAI_API_KEY = "sk-..."
openonyx chat --provider openai --model gpt-4o --effort medium --auto-save
Linux / macOS:
export OPENAI_API_KEY="sk-..."
openonyx chat --provider openai --model gpt-4o --effort medium --auto-save
With OpenRouter or any compatible gateway:
openonyx chat --provider openai --api-base https://openrouter.ai/api/v1 --model anthropic/claude-sonnet-4 --auto-save
Option C — Local Models (Ollama, vLLM, LM Studio)
Whenever --api-base (or OPENAI_API_BASE / OPENAI_BASE_URL) is set, OPENAI_API_KEY is optional.
Ollama:
openonyx chat --provider openai --api-base http://localhost:11434/v1 --model qwen2.5-coder:14b --effort low --auto-save
vLLM / LM Studio:
openonyx chat --provider openai --api-base http://localhost:8000/v1 --model Qwen/Qwen3-Coder-30B-A3B --auto-save
Tip: passing
--auto-save(or settingONYX_AUTO_SAVE=1) automatically stores snapshots and transcripts together under.onyx/vault/<timestamp>_<model>_<branch>/(auto-ignored by Git), keeping your repository root clean while enabling/rewindand--resumeout of the box.
3. Your First Interactive Session (openonyx chat)
- Open a terminal inside any Git repository (or pass
-w /path/to/repo). - Run
openonyx chat --snapshot-dir .snaps_demo --record demo.tr. - The TUI displays:
- Compact 3-row header: Braille activity emblem,
[BUILD]/[PLAN]badge,[SANDBOX:workspace], active model & effort, and live telemetry (ctx,in/cache/out/thinktokens, and estimated cost orlocal). - Main
Memory & Tracepane: conversation turns, tool calls, observations, and live[stream] ...▍token previews. - Bottom input bar: prompt input and key hints.
- Compact 3-row header: Braille activity emblem,
Step 1 — Explore Safely in [PLAN] Mode
Press Tab to toggle to [PLAN] (read-only; mutating tools are unconditionally blocked). Type an analysis prompt and press Enter:
Inspect this repository structure and propose a concise plan to add a helper function to the main module.
The agent uses read-only tools (glob_files, scent_outline, code_search, fs_read, plan_update) without interrupting you for approval. When your terminal is at least 100 columns wide and plan_update is used, the Live Plan panel opens automatically on the right.
Step 2 — Switch to [BUILD] and Review Diffs
Press Tab again to switch back to [BUILD] and send a follow-up prompt:
Implement the change and run the test suite.
Whenever the agent proposes fs_edit, fs_write, or shell_exec, the TUI pauses in WaitingApproval:
- The banner shows which agent requested the action (
[agent #1 ...]). - File edits show a colorized unified diff preview before writing to disk.
- You can scroll
Memory & Tracefreely (Up/Down/PgUp/PgDn) while inspecting the diff. - Press
yto approve ornto deny (denials are fed back to the agent cleanly).
Step 3 — Revert the Last Edit with /undo
If you want to roll back the latest fs_edit or fs_write, type:
/undo
openonyx restores the lightweight Git tree checkpoint captured right before the edit — without touching HEAD or your staged index — and cleanly removes newly created untracked fs_write files while preserving unrelated untracked files.
Step 4 — Exit Cleanly
Press Esc or Ctrl+C. openonyx flushes the final exit milestone into .snaps_demo/snapshots.onyxpack and writes demo.tr.
4. Resume, Inspect, or Replay Offline
After closing your session, try these zero-token commands:
# 1. List all recorded milestones and Git tree checkpoints
openonyx inspect .snaps_demo --list
# 2. Deterministically replay the session offline (0 HTTP calls, 0 disk writes)
openonyx replay demo.tr
# 3. Resume from the latest milestone
openonyx chat --resume .snaps_demo
# Or branch safely from an earlier tick into a sibling fork directory
openonyx chat --resume .snaps_demo --tick 8
5. Single-Turn Headless Execution (openonyx run)
For scripts or CI pipelines where you don't want a TUI:
openonyx run "summarize the pending git diff" --record run.tr --snapshot-dir .snaps_run
openonyx prints the final agent response along with [openOnyx telemetry] token/cost counters.
← English Index · Versión en Español · Next: 02. TUI & Daily Workflow →
02. TUI & Daily Workflow
This chapter explains every visual component of openonyx chat, how to tune reasoning effort (--effort) and hot-swap the LLM target, how multi-turn memory and tiered context (/compact) work, how to navigate the five ephemeral F1..F5 views (with the Ctrl+K palette and /view), and how to supervise subagents from the F2 Agents view (or the /agent picker).
1. TUI Anatomy
Running openonyx chat organizes the terminal into four zones:
┌ F1 Chat · F2 Agents · F3 Sprout · F4 Plan & Diff · F5 Timeline · Esc:Quit ──────────────┐
│ openOnyx [BUILD] [SANDBOX:workspace] · gemini/gemini-2.5-pro (effort:high) │
│ goal: Refactor the parser… · phase: thinking / streaming… · #1 [root] [subagents:1] │
│ ⠋ Tab: Plan/Build · F2: Agents · /rewind · /fork · /services · Esc: quit │
└─ ctx: 24% · in: 18.4k (cache 12.1k) · out: 1.9k · think: 0.6k · ~$0.024 ────────────────┘
┌─ Memory & Trace (Up/Down/PgUp/PgDn/Home/End) ──────────┐┌─ Live Plan ───────────────────┐
│ [user] Refactor the parser... ││ [x] Inspect AST │
│ [call] scent_outline {"path":"src/parser.rs"} ││ [>] Edit parser.rs │
│ [obs] @TOON v1 ... ││ [ ] Run cargo test │
│ [stream] Updating range validation...▍ │├───────────────────────────────┤
│ ││ Services (Sprout) │
│ ││ [READY] postgres (5432) │
│ ││ [READY] api (8080) │
└────────────────────────────────────────────────────────┘└───────────────────────────────┘
┌─ [BUILD] Goal / Command (Enter send · Tab Plan/Build · F2 Agents · /rewind · /fork …) ──┐
│ > _ │
└─────────────────────────────────────────────────────────────────────────────────────────┘
Compact Header (Tabs + Title + Body + Telemetry)
- Tab strip (top row, right-aligned):
F1 Chat · F2 Agents · F3 Sprout · F4 Plan & Diff · F5 Timeline, with the active view in bold white. It ends withEsc:QuitinF1 ChatorEsc:Backin the ephemeral views; when an approval is pending outsideF1 Chat, it is replaced by the red [F1 Chat !APPROVAL] badge (blind approval is forbidden:y/nnever approve or deny in the other views). - Title row:
openOnyx [BUILD] [SANDBOX:workspace] · gemini/gemini-2.5-pro (effort:high)— mode badge ([BUILD]/[PLAN]/[EXPLORE]), sandbox badge ([SANDBOX:workspace|strict|off]), the[UNTRUSTED]tag when the workspace is untrusted, and the live LLM targetprovider/model (effort:low|medium|high|auto), hot-swapped by/profile//provider//model//effort(section 2.1). - Body rows:
- Animated Braille emblem (
6×3sub-pixel canvas, throttled to 90 ms) rotating smoothly while work is in progress (thinking,acting,waiting_children) and resting when idle or awaiting approval. - Goal & phase: the focused agent's
goal:andphase:with its ID/name/role (#1 openonyx-1 [root]), the[subagents:N · bg:M · F2](or[N/M agents · F2]) and[queued:N]tags, and — when session saving is active (--auto-saveor--snapshot-dir) — the livevault:<session>badge (automatically updated when branching via/forkor/rewind). - Agent strip or quick hints: when multiple agents exist, renders a compact single-line agent strip; otherwise shows quick hints.
- Animated Braille emblem (
- Bottom border (Live Telemetry):
- Approximate context window fill (
ctx: <1%orXX%, plus[compacted]after/compact). - Cumulative provider counters:
in,cache(prompt cache hits),out, andthink(reasoning tokens when reported). - Estimated USD cost (
~$0.024) for known cloud models, orlocalwhen using a custom--api-base. - Telemetry lives outside the EAV graph so it never perturbs deterministic ticks, snapshots, or replay.
- Approximate context window fill (
Memory & Trace Pane & History Navigation
- Displays the full trace of the focused agent: user prompts, tool calls (
[call]), observations ([obs]), model replies, system notes ([system]), and live SSE previews ([stream] ...▍, rendered inpump_idlewithout advancing ticks). - Smooth scrolling: use
Up,Down,PgUp,PgDn,Home,End,Ctrl+U, andCtrl+Deven while an approval box is open. Scrolling up shows[SCROLLED -N lines | End to follow]; pressingEndor submitting a prompt snaps back to auto-follow.
Automatic Side Panels (>= 100 Columns)
When terminal width is at least 100 columns, the center area splits 70% (Memory & Trace) / 30% (right side):
Live Plan: opens automatically whenplan_updaterecords steps ([x]done,[>]in progress,[ ]pending).Services (Sprout): opens when a validsprout.tomlexists in the workspace, showing color-coded service states ([READY],[STARTING],[PENDING],[FAILED],[OFF]).- When both are active, the right pane splits vertically
50%/50%.
Approval Box with Colorized Unified Diff (y / n)
Whenever an agent requests a mutating tool (fs_write, fs_edit, shell_exec, service_start, service_stop, service_exec) requiring confirmation:
- The banner identifies the requesting agent explicitly:
[agent #id name]. - For
fs_writeandfs_edit(including atomic multi-hunk edits), a colorized unified diff preview is rendered before anything touches disk. - Press
yto approve ornto deny. - Only from
F1 Chat: in the ephemeralF2..F5views,y/nnever approve or deny; the tab strip shows the[F1 Chat !APPROVAL]badge to remind you to return toF1and review the diff and the# impact:line.
2. Tuning Reasoning Effort (--effort)
Control how much internal reasoning budget the model spends:
| Value | Gemini (thinkingLevel) | OpenAI-compatible (reasoning_effort) | Recommended Use |
|---|---|---|---|
low | LOW | low | Quick lookups, read-only tasks, lightweight local models |
medium | MEDIUM | medium | Everyday editing, debugging, and refactors |
high | HIGH | high | Architecture design, subtle bugs, deep audits |
Set via flag or environment variable (precedence: --effort > ONYX_EFFORT > GEMINI_THINKING_LEVEL / OPENAI_REASONING_EFFORT):
openonyx chat --effort high --auto-save
# or via environment variable:
export ONYX_EFFORT=medium
For
anthropic: the effort maps to an extended-thinking budget (thinking.budget_tokens:low2048 /medium8192 /high16384 tokens) when no explicit budget is set. You can pin it with--thinking-budget <n>(orANTHROPIC_THINKING_BUDGET;0= off, range1024..=60000), which also raisesmax_tokensabove the budget. The provider also supports prompt caching (cache_control: ephemeralon the system block and the last tool definition) and automatic retries on429/529(chapter 06).
2.1 Hot-Swapping the LLM Target (/profile, /provider, /model, /effort)
Beyond effort, the full LLM target (provider, model, api_base, and effort) is hot-swappable without restarting the session:
- Profiles:
[[llm_profiles]]blocks in.onyx/config.toml(trusted workspace) withid,provider(gemini|openai|anthropic),model,effort, optionalapi_base, and optionalapi_key_env. Never literal keys in the file (details in chapter 03). - Slash commands:
/profile [id]lists or applies a profile,/provider <gemini|openai|anthropic>,/model <name>, and/effort <auto|low|medium|high>. Changes apply at the next tick boundary and are sealed in theONYXTR2transcript (deterministic replay). - Live header: the title row switches to showing
provider/model (effort:...)of the active target instead of the startup one. Ctrl+Kpalette: a typing-free alternative — filter profiles, providers, and efforts, then run withEnter(LLM actions go through the deterministic bus exactly as if typed; a profile without credentials is shown asunavailablewith its reason and is not selectable).- Web UI (
openonyx serve): the LLM target button (brand subtitle) opens a modal dialog with profile/model/effort and Apply/Cancel buttons, without exposing credentials to the browser.
Credentials never live in the config: each profile resolves its key via
api_key_env(or the provider's standard variable →ONYX_API_KEY). A profile missing its key or with a rejectedapi_baseis listed asunavailablewith the actionable reason.
3. Multi-Turn Conversations, Active-Root Guard & /new
Automatic Continuation (continue_agent)
Once a turn finishes (Settled), submitting a follow-up prompt reactivates the same root agent via continue_agent, preserving its entire rel_memory with monotonic step counts rather than spawning an amnesic agent.
Follow-Up Prompt Queue While Busy (queued:N)
While the root agent is actively working (thinking, acting, waiting_children, or waiting_approval), you can type your next follow-up and press Enter: instead of racing a second root agent over the workspace, the TUI queues it automatically (queued:N shown in the header and input border, previewed when the input is empty, and clearable anytime with Ctrl+X) and dispatches it the moment the current turn settles. Immediate commands (/agent, /mode, /services, /service, /undo) still execute right away.
/ & @file Autocomplete, Cursor Editing & Input History
- Visible UTF-8 cursor: edit anywhere inside the prompt using
Left,Right,Home,End,Backspace, andDelete. - Prompt history: cycle previous prompts with
Alt+Up/Alt+Down(orCtrl+P/Ctrl+N), restoring your unsent draft when returning to the bottom. /popup: typing/at the start of the line opens a floating command menu with short descriptions (↑/↓,Tab/Enterto accept,Escto dismiss).@popup: typing@at the start of a word (e.g.review @tui) fuzzy-filters cached workspace paths (respecting ignored directories and.onyx/vault) and inserts the clean relative path onTab/Enter.
Starting Fresh (/new)
/new: marks the next prompt to spawn a clean root agent with fresh memory./new <goal>: immediately spawns a fresh root agent with<goal>and auto-focuses it in the TUI.
4. Tiered Context & /compact [focus]
To prevent long sessions from overflowing context windows or burning unnecessary tokens, openonyx uses a shared Tier 0 / Tier 1 / Tier 2 context engine across both Gemini and OpenAI:
- Tier 0 (Full): the latest 10 tool observations are kept verbatim.
- Tier 1 (Coordinate-Preserving Summaries): older outputs from
fs_read,scent_outline,scent_impact,code_search,glob_files, andshell_execare deterministically summarized while keeping paths, line ranges, and exit codes, maintaining cache-stable prefixes for prompt caching. - Tier 2 (
/compact& Auto-Compaction): upon reaching the auto-compact threshold (80%of context budget) or running/compact [focus],CommandSpawnerSysteminserts a verified[session_summary]boundary.
/compact
/compact jwt authentication and middleware
Providing a [focus]:
- Rescues
files_foundand keyword-matchedfocus_matchesfrom earlier turns. - Drops active
ctx:fill immediately on the next turn. - Records a
cmd:/compactmilestone insnapshots.onyxpack. - Loses nothing: pre-compact ticks remain intact in the graph and
snapshots.onyxpackforinspect,replay, andrewind.
5. Modular F1..F5 Views, Ctrl+K Palette & /view
Besides F1 Chat (trace, side panels, input, approvals), the TUI exposes four ephemeral views you can jump to with the function key, /view <name>, or the Ctrl+K palette:
| View | Key | Slash | Contents |
|---|---|---|---|
F1 Chat | F1 | /view chat | Memory & Trace, Live Plan / Services (Sprout) panels, input and approvals |
F2 Agents | F2 | /view agents | Graph agents + async [bg] jobs (with a → <driver> badge when an external CLI harness runs the worktree) |
F3 Sprout | F3 | /view sprout | sprout.toml services (status badges) + live logs of the selected service |
F4 Plan & Diff | F4 | /view plan | Active plan (ws.plan.text) on top + Git effects ledger (tick, tool, target, reversibility, (undone)) below |
F5 Timeline | F5 | /view timeline | snapshots.onyxpack milestones (tick, tag, size, checksum) for /rewind / /fork |
- 100% ephemeral navigation: switching views writes nothing to the graph, emits no bus events, and advances no ticks — it is just a different "lens" over the same deterministic state.
F2 Agents:Up/Downselect (the focused agent carries the*marker),Enterfocuses that agent'sMemory & Traceand returns toF1 Chat,Escreturns toF1 Chat.F3 Sprout:Up/Down/PgUp/PgDnnavigate services;s/x/r/a(start/stop/restart/all) andf(log follow) are gated: inPLAN/EXPLOREmode or with an[UNTRUSTED]workspace the view header showsMUTATIONS BLOCKEDand the action is rejected with a notice.F4 Plan & Diff:Up/Downscroll the Git effects ledger.F5 Timeline:Up/Downselect a milestone,Enterruns/rewind <tick>,fruns/fork.Esc: closes popups or the palette if open; inF1 Chatit quits cleanly; inF2..F5it returns toF1 Chat(the tab strip label readsEsc:QuitorEsc:Back)./view <chat|agents|sprout|plan|timeline>(case-insensitive): intercepted atEnterat the TUI level — 0 bus events, 0 ticks, 0 graph writes./viewwith no argument shows usage; an unknown name shows a transient notice.Ctrl+Kpalette: centered popup (Ctrl+K Palette — type to filter) with three groups — VIEW (F1..F5), LLM ([[llm_profiles]]profiles, providers, and efforts) and AGENT (by ID/name). Type to filter (every printable character filters —j/kincluded, they never navigate),Up/Down(orCtrl+P/Ctrl+N) select,Enterexecutes,Esc/Ctrl+Kclose. It has top priority (exceptCtrl+C) and swallows every key while open; LLM actions are sent through the deterministic bus and sealed inONYXTR2, exactly as if typed.
6. Multi-Agent Workflow: Subagents, F2 Agents View & /agent
The root agent can delegate subtasks in two ways: synchronous graph subagents (spawn_agent, sharing the workspace and awaited by the parent) and asynchronous jobs in isolated Git worktrees (spawn_subagent / /spawn, chapter 05).
- Safe default step cap: synchronous subagents inherit a default cap of
32steps (DEFAULT_SUBAGENT_MAX_STEPS, overridable viamax_stepsinspawn_agentJSON args) to prevent runaway loops in local models. While children are active, the parent entersWaitingChildren. - Live inspection with the
F2 Agentsview: pressF2anytime to jump to the full-screen Agents view:- Lists every graph agent (root and subagents) with ID, name, role (
root/sub), current state, and goal. - Also lists async
[bg]jobs with their status (running,done,merged,failed), worktree branch, and — when an external harness runs the job — a→ <driver>badge. Up/Downselect,Enterfocuses the agent'sMemory & Trace(back toF1 Chat),Escreturns toF1 Chat.
- Lists every graph agent (root and subagents) with ID, name, role (
- Alternative shortcuts:
/agent(or/agents): opens the centered Agent Selector popup (or cycles to the next agent when only one exists)./agent <id|name>: jumps directly to an agent (e.g./agent 1or/agent researcher).Ctrl+K: the palette also lists agents;Enterfocuses and returns toF1 Chat.Ctrl+Tab: quick-cycles focused agents (terminal-dependent alias;F2,/agent, and the palette work everywhere).
- External drivers from the Web UI: in
openonyx serve, the Subagent driver selector picks a declared[[external_drivers]]; sending free text with a non-native driver makes the browser emit/spawn --driver <id> <text>(chapter 05).
7. Interactive Time Debugger (TimeFreeze, SDD-07)
TimeFreeze lets you pause the session at any tick and step through it without spending tokens or touching disk: tick boundaries live in a RAM ring (on-disk milestones from --snapshot-dir overlay it as references) and the whole state is 100 % ephemeral until you confirm a branch (/go with the cursor anchored in the past creates the fork; nothing is written before that).
Freezing, scrubbing, and getting out
| Action | How |
|---|---|
| Freeze / unfreeze at the cursor | Ctrl+T or /time (ephemeral toggle) |
| Scrub −1 / +1 over available ticks | Alt+← / Alt+→ (looking at the past auto-freezes) |
| Return to present without quitting the app | Esc while TIME FROZEN (a second Esc when live: exit) |
Jump to a specific tick (milestones [pack:*], [ram], (present)) | F5 Timeline → Down/Up → Enter |
While frozen, the amber banner appears (⏸ TIME FROZEN · tick X / present Y + the files that would be reverted when branching, RAM-only) and plain prompts are blocked: an out-of-order turn would break the bit-for-bit replay. The escape routes (/… and !…) keep working always, even with the agent busy in Thinking (the pre-LLM breakpoint): they run immediately, never queued.
0-token primitives and frozen-graph surgery
| Command | What it does |
|---|---|
/step [n] | Advance n deterministic ticks with 0 LLM calls (default 1; works frozen) |
/step-llm | Exactly one LLM turn: gate + branch if needed + re-freeze when it answers |
/go (alias /unfreeze) | Branch from the cursor if it looks at the past, then resume at present |
! <cmd> | Run a deterministic shell command in the sandbox and seal the result (0 network, 0 disk) |
/read <path> [a..b] | Read a file (or line range) into memory, 0 tokens, frozen-safe |
/inject <text> | Stage a sealed user memory into the timeline (0 tokens) |
/graph inspect [agent|mem|ws] | Read-only report of the frozen graph (memories with mem_seq, agents, workspace) |
/graph drop-mem <seq|a..b> | Drop memories by mem_seq without advancing time |
/graph edit-mem <seq> <text> | Edit an existing memory in place |
/graph set-goal <text> | Change the root agent's goal inside the frozen graph |
These primitives are sealed into ONYXTR2 (/__onyx_det_*): offline replay reproduces them bit-for-bit with 0 I/O and 0 network. The Web/PWA view (openonyx serve) has full parity: the #tick-pill opens the same amber bar, POST /api/v1/time/scrub applies ephemeral scrubs, plain prompts under freeze get an actionable 409 Conflict, and root memories expose ✎/× buttons — see chapter 04.
Non-goal: Sprout (services/containers) and MCP server effects are external process side effects, not graph mutations:
TimeFreezedoes not rewind them (nor revert them when branching).
8. Quick Reference of Keys & Slash Commands (chat)
| Key / Command | Action |
|---|---|
Enter | Submit goal, follow-up prompt, or slash command |
Tab | Toggle [BUILD] ↔ [PLAN] in place |
F1..F5 | Switch ephemeral view (Chat, Agents, Sprout, Plan & Diff, Timeline) |
Ctrl+K | Open the command palette (views + LLM slash commands + agents); type to filter, Enter executes |
Ctrl+Tab | Quick-cycle focused agent (terminal-dependent alias for F2 / /agent) |
y / n | Approve or deny a pending mutating tool diff (only in F1 Chat; other views hint to press F1) |
Up/Down/PgUp/PgDn/Home/End/Ctrl+U/Ctrl+D | Scroll Memory & Trace history |
Alt+← / Alt+→ | TimeFreeze: scrub the cursor −1/+1 over available ticks (auto-freezes when looking at the past) |
Ctrl+T | TimeFreeze: toggle freeze at the cursor / return to present (ephemeral, 0 disk) |
Esc | Close popup/palette; while TIME FROZEN return to present without quitting; in F2..F5 back to F1 Chat; in F1 Chat exit cleanly (flushing snapshot & transcript) |
Ctrl+C | Exit cleanly (flushing exit snapshot & transcript, if configured) |
/view <chat|agents|sprout|plan|timeline> | Switch views from the prompt (ephemeral: 0 bus events, 0 ticks, 0 graph writes) |
/agent [id|name] | Open agent selector or focus specific agent |
/mode [plan|build|explore] | Switch mode explicitly or toggle PLAN ↔ BUILD |
/undo | Revert latest reversible Git checkpoint (also cleans newly created fs_write files) |
/rewind [tick] | List milestones or rewind live to <tick> into a safe sibling fork |
/fork [name] | Branch snapshots up to current tick into a sibling directory |
/time | TimeFreeze: toggle freeze at the current cursor (ephemeral, 0 disk) |
/go (alias /unfreeze) | TimeFreeze: branch if the cursor looks at the past, then resume at present |
/step [n] | TimeFreeze: n deterministic ticks with 0 LLM (default 1; frozen-safe) |
/step-llm | TimeFreeze: exactly one LLM turn (gate + branch + re-freeze) |
! <cmd> | Deterministic sandboxed shell with the result sealed into ONYXTR2 (frozen-safe) |
/read <path> [a..b] | Read a file (or range) into memory, 0 tokens (frozen-safe) |
/inject <text> | Sealed user memory staged into the timeline, 0 tokens (frozen-safe) |
/graph <inspect|drop-mem|edit-mem|set-goal> | Read-only inspection or surgery on the frozen graph (memories by mem_seq, goal) without advancing time |
/compact [focus] | Compact older turns while rescuing focus matches and discovered files |
/services | Print @TOON v1 status of services defined in sprout.toml |
/service <start|stop|logs> <id|all> [tail] | Control Sprout services directly from the TUI |
/new [goal] | Prepare or immediately launch a fresh root agent |
/profile [id], /provider <gemini|openai>, /model <name>, /effort <auto|low|medium|high> | Hot-swap the LLM target (section 2.1) |
/spawn [--driver <id>] <goal> | Launch an async job in an isolated Git worktree (chapter 05) |
/subagents | List async [bg] jobs (status, branch, touched files) |
/merge <job_id> | 3-way merge the job's worktree (Ask/Deny governance, chapter 03) |
/discard <job_id> | Cancel the job and remove its worktree and temp branch |
← 01. First Steps · English Index · Next: 03. Modes, Permissions & OS Sandbox →
03. Modes, Permissions & OS Sandbox
openonyx enforces defense in depth across every agent action: workspace modes, declarative .onyx/config.toml rules, read-only Control Plane protection, strict environment sanitization (env_clear()), OS-level sandboxing, and RAII process-tree supervision.
1. Workspace Modes: PLAN, BUILD & EXPLORE
The active mode (ws.mode) lives inside the EAV graph and is recorded in ONYXTR2 transcripts so rewind and replay reproduce it faithfully.
| Mode | Read / Search / AST | Mutations (fs_write, fs_edit, shell_exec, service_start/stop/exec) | Best For |
|---|---|---|---|
BUILD (default) | Allowed | Allowed with approval (or per .onyx/config.toml rules). fs_edit requires prior fs_read. | Implementation, refactoring, running tests. |
PLAN | Allowed | Unconditionally blocked (even with allow rules or --auto-approve). | Architecture analysis, design planning, PR reviews. |
EXPLORE | Allowed | Unconditionally blocked. | Safe read-only exploration of unfamiliar repositories. |
Dynamic MCP tools: even though an
mcp__<server>__<tool>call may not mutate the local filesystem, a remote MCP server can execute processes or network traffic outsideopenonyx's control, so it is treated like a mutation and isDenyinPLAN/EXPLORE(section 2.8).
Switching Modes in chat
- Press
Tabto toggle[BUILD]↔[PLAN]in place. - Or run
/mode plan,/mode build,/mode explore(or/modewith no argument to togglePLAN↔BUILD).
2. Declarative Permissions (.onyx/config.toml)
Granular rules are loaded and merged automatically from two locations:
- Global user config:
~/.onyx/config.toml - Project config:
<workspace>/.onyx/config.toml
Security invariant: project config can never remove a global
denyrule defined in~/.onyx/config.toml.
Precedence: deny > ask > allow
deny: blocks the tool unconditionally — even when--auto-approveis active. Only bypassed if you explicitly pass--ignore-deny.ask: requires interactive confirmation (y/n), prevailing overallowat equal or higher specificity.allow: auto-approves matching calls inBUILDmode without interrupting you (PLAN/EXPLOREstill block all mutations). A more specificallow(e.g.shell_exec(cargo test*)) overrides a generic wildcardask(shell_exec(*)).
Complete .onyx/config.toml Example
[permissions]
# Hard blocks (enforced even with --auto-approve)
deny = [
"shell_exec(rm -rf*)",
"shell_exec(git push*)",
"shell_exec(curl*)",
"fs_write(.env*)",
]
# Auto-approve safe verification commands in BUILD mode
allow = [
"shell_exec(cargo check*)",
"shell_exec(cargo test*)",
"shell_exec(cargo clippy*)",
"shell_exec(cargo fmt --all -- --check)",
]
# Prompt for all other shell executions and file writes
ask = [
"shell_exec(*)",
"fs_write(*)",
"fs_edit(*)",
]
[sandbox]
# "workspace-write" (default) | "strict-container" | "off"
mode = "workspace-write"
# "offline" (default) | "localhost" | "unrestricted"
network = "offline"
# Extra env vars allowed after env_clear() (never pass API keys)
env_passthrough = ["RUST_LOG", "RUST_BACKTRACE"]
# Additional read-only paths outside workspace (optional)
allow_read_paths = []
# Resource limits for child processes
max_memory_mb = 4096
max_pids = 128
# OCI image when mode = "strict-container" (optional)
# container_image = "rust:1.85-slim"
[impact]
# Scent-Heated Approval: escalates Allow -> Ask when a diff touches public symbols with callers
enabled = true
max_hops = 2 # clamped 1..=4
ask_heat_bp = 2500 # threshold for public scope:src symbols (basis points 0..=10000)
hard_ask_bp = 8000 # hard threshold for any high-fanout symbol
[verify]
# Verify-on-Edit: after each successful fs_edit/fs_write, run the rules whose glob
# matches the edited file (section 2.9). Off by default.
on_edit = true
max_secs = 20 # default per-rule timeout (clamped 1..=120)
[[verify.rules]]
glob = "**/*.rs"
command = "cargo test --workspace"
# max_secs = 60 # per-rule timeout override (optional)
Monotonicity of Scent-Heated Approval:
[impact]can only escalateAllow → Askand display# impact: N callers, H hops, scope:src(pub) [heat Xbp]above the diff in TUI/CLI. It never overridesdeny, never relaxesasktoallow, and degrades gracefully to static rules when unindexed orenabled = false.
2.5. Workspace Trust (~/.onyx/trusted_workspaces.toml)
To defend against malicious cloned repositories or untrusted PRs (Indirect Prompt Injection + allow = ["shell_exec(*)"] or arbitrary sprout.toml commands), openOnyx pins blake3 hashes of .onyx/config.toml and sprout.toml per workspace in ~/.onyx/trusted_workspaces.toml:
- Clean repository (no
.onyx/config.tomlorsprout.toml): zero friction (no-project-config). - Untrusted or modified repository (
untrusted/modified,[UNTRUSTED]badge in TUI):- Project
.onyx/config.tomlcan only tighten policy (deny/ask, stricter sandbox/impact); projectallowrules,env_passthrough,allow_read_paths,container_image, and any[sandbox]/[impact]relaxations are ignored. sprout.tomlblocks service execution (service_start,service_exec,stop_cmd) until explicitly approved.
- Project
- Trust commands:
openonyx trust(approve current workspace),openonyx trust check,openonyx trust list,openonyx trust revoke, per-run--trust-workspace, or/trust [status|revoke]inside the TUI.
2.6. LLM Profiles ([[llm_profiles]])
The LLM target (provider, model, api_base, effort) can be declared in .onyx/config.toml as [[llm_profiles]] blocks and hot-swapped with /profile / /provider / /model / /effort (chapter 02, section 2.1):
[[llm_profiles]]
id = "local-ollama"
provider = "openai"
model = "llama3.1:70b"
effort = "medium"
api_base = "http://localhost:11434/v1"
# api_key_env = "OLLAMA_API_KEY"
- Fields:
id(unique),provider(gemini|openai|anthropic),model,effort(auto|low|medium|high), optionalapi_base, and optionalapi_key_env. Unknown or duplicate keys are an actionable parse error. - Never literal keys: a literal
api_keyin the block is rejected by the parser with an error pointing toapi_key_env(and the message never echoes the key value). Credentials are always resolved from environment variables (api_key_env→ the provider's standard variable →ONYX_API_KEY). api_basevalidated at registration: same policy as--api-base(http://only on loopback; remote hosts requirehttps://; non-official hosts require--allow-custom-auth-host).- Trust gate: an untrusted workspace ignores its
[[llm_profiles]]blocks and shows the warningignored N [[llm_profiles]] block(s); run openonyx trust or /trust to approve. With a trusted workspace, precedence is global (~/.onyx/config.toml) < project (merge replace-by-id). - Availability: a profile with no resolved key or a rejected
api_baseis listed asunavailablewith the actionable reason (/profile,Ctrl+Kpalette, and the Web selector). The TUI and Web only expose metadata (public_snapshot): provider, model, effort, reason — never keys.
2.7. External CLI Harnesses ([[external_drivers]])
Async spawn_subagent / /spawn jobs (chapter 05) can run outside the OnYX engine by delegating the work to an external CLI harness declared in .onyx/config.toml:
[[external_drivers]]
id = "opencode"
bin = "opencode"
args = ["run", "--model", "qwen38-27b"]
# prompt_transport = "stdin" # "stdin" (default) | "arg" | "temp_file"
# prompt_flag = "--prompt-file" # for "temp_file" (or {prompt_file} placeholder in args)
timeout_secs = 600
allowed_env = []
# inherit_home = true # if the CLI needs config/OAuth from the real HOME
# network_allowlist = ["api.example.com"]
- Fields:
id(charset[a-z0-9_-]),bin(resolved onPATH/PATHEXT),args(fixed arguments),prompt_transport(stdinrecommended and default;argis rejected on Windows when the binary resolves to a.cmd/.batwrapper;temp_filefor large prompts, kept out of the Git index),prompt_flag,timeout_secs,allowed_env(env whitelist for the child), andinherit_home(defaultfalse). - Trust gate: an untrusted workspace cannot launch external drivers (absolute
Deny:requires a trusted workspace). - Default
Askapproval:spawn_subagentwith an external driver never auto-approves: without explicitask/allowrules the decision isAsk; you can pin it withallow = ["spawn_subagent(opencode)"]orask/denywith the same pattern (adeny spawn_subagent(opencode)blocks that driver even with anallow). - Process isolation: the prompt is delivered without shell injection (stdin / single argv / temp file); the child environment goes through
env_clear()+allowed_env; the process is bound to aProcessJobatspawn(iftimeout_secselapses or the job is cancelled, the whole tree dies; on Windows there is ataskkill /F /T /PIDfallback); and the full log is sealed in.onyx/vault/subagent-logs/<job_id>.logafter passing throughscrub_secrets. - Declarative network (
network_allowlist): this is declarative governance: it is enforced in-container only under--sandbox strict-container; under the other profiles it is advisory (doctortells you so). An empty allowlist meansLocalhostOnly; with an allowlist, the sandbox does not inject*_OFFLINEvariables (the harness must reach its API). - Merge forced to
Ask: even if your permissions would auto-approve,subagent_mergefor a job with an external driver requires explicit approval (ExternalDriverApprovalPolicy).
2.8. MCP Servers ([mcp.servers.<name>])
openonyx can connect Model Context Protocol (MCP) servers declared in config.toml (global ~/.onyx/config.toml and, with a trusted workspace, <workspace>/.onyx/config.toml):
[mcp.servers.github]
transport = "stdio"
command = "npx"
args = ["-y", "@modelcontextprotocol/server-github"]
# env = { GITHUB_TOKEN = "${GITHUB_TOKEN}" } # ${VAR} refs expanded at spawn time
timeout_secs = 20 # default 20
# enabled = true # default true
[mcp.servers.docs]
transport = "http"
url = "https://mcp.example.com/sse"
# headers = { Authorization = "Bearer ${MCP_DOCS_TOKEN}" }
- Fields:
transport("stdio"withcommand/args/env, or"http"withurl/headers),timeout_secs(default20s per JSON-RPC call), andenabled(defaulttrue). Server names cannot contain__(reserved for themcp__<server>__<tool>prefix).${ENV_VAR}references are expanded only when the process/request launches (never logged or persisted), andAuthorization/X-Api-Keyinheadersrequire${VAR}. - Merge & Trust gate: replace-by-name merge with precedence
global < workspace; an untrusted workspace ignores its[mcp.servers.*]with the warningMCP config in ... ignored: workspace is not trusted (use --trust-workspace or openonyx trust), while the global config always applies. - Naming & approval: every discovered tool (
tools/list) is exposed to the LLM asmcp__<server>__<tool>withrequires_approval = true: it always asks for interactive approval inBUILDunless a more specificallowrule says otherwise (e.g.allow = ["mcp__github__search_repos"]orallow = ["mcp__github__*"]);ask/denyglobs work too (deny = ["mcp__*"]blocks all MCP). PLAN/EXPLORE=Deny: in those modes everymcp__*call is unconditionally blocked (a remote server executes processes/network outside the sandbox).- Failure isolation: a dead server never aborts the session: it is reported as
[openOnyx mcp] server \` unavailable: ... and the rest of the session continues; each server exposes its status foropenonyx doctor`. - stdio session safety: JSON-RPC 2.0 with a dedicated reader thread, a real per-call timeout (
mpsc::recv_timeout), a 4 MiBstdoutline cap, andProcessJobprocess-tree teardown on failure (Windows and Unix). - Sanitized output:
tools/callresults and discovery errors pass throughtruncate_utf8+scrub_secretsbefore reaching the LLM or the transcript. openonyx doctor: audits each declared server with a 5 s-capped handshake (min(timeout_secs, 5)):Connected/Disabled→[CHECK], failure → actionable[ERR](already scrubbed message), untrusted workspace →[WARN]without workspace discovery.- 0-I/O
replay: replaying anONYXTR2transcript never contacts a server: themcp__*tools are reconstructed from the transcript itself (extract_mcp_tools_from_transcript), withoutload_mcp_registry.
2.9. Verify-on-Edit ([verify] / [[verify.rules]])
Verify-on-Edit closes the edit → verify loop inside the agent's turn: after each successful fs_edit/fs_write, openonyx runs the commands whose rules match the edited file and appends the outcome to the tool's observation, so the model can fix the error before the turn ends.
[verify]
on_edit = true # default false: explicit opt-in, 0 overhead when unset
max_secs = 20 # default per-rule timeout (clamped 1..=120)
[[verify.rules]]
glob = "**/*.rs" # relative-path glob (compile_glob_regex)
command = "cargo test --workspace"
# max_secs = 60 # per-rule timeout override (optional)
[[verify.rules]]
glob = "src/**"
command = "pnpm test"
- Rule scope: a rule fires when its
globmatches the edited file or (when a Scent index exists) ascope:testfile reachable by AST impact within ≤ 2 hops; in an unindexed workspace only the edited path is matched. - Execution: every
commandgoes through the same sandbox pipeline asshell_exec(prepare_sandboxed_shell_command+configure_process_isolation+ProcessJobRAII +env_clear()+ timeout cancellation +scrub_secrets), with captured diagnostics capped at 4 KiB. - Outputs injected into the tool observation:
\n[verify: PASS] <N> rule(s) succeeded (<cmds>)— plusimpacted_tests: [...]when the Scent index identifies reachablescope:testfiles;\n[verify: FAIL] <cmd> (exit <code> | timed out after <N>s)\n<diagnostics>\n(Fix the error before finishing the turn.);\n[verify: BLOCKED] <cmd> (denied by [permissions])— the rule is not executed.
[permissions].denygovernance: eachcommandis evaluated asshell_execbefore running; adenyblocks the rule ([verify: BLOCKED]) and stops the verification loop for that edit.- Workspace Trust Gate: merge precedence is
global (~/.onyx/config.toml) < workspace (<workspace>/.onyx/config.toml, trusted); an untrusted workspace ignores its[verify]/[[verify.rules]]entirely (with an actionable warning inpolicy.trust_warnings), while the global config still applies. Trusted workspace rules replace the global set.
3. Read-Only Control Plane Protection
Even in BUILD mode with --auto-approve, onyx-workspace protects sensitive control-plane paths as read-only:
.onyx/config.toml(prevents an agent from widening its own permissions or disabling the sandbox)..onyx/vault/**(prevents an agent from deleting or tampering with session snapshots and transcripts)..git/hooks/**and.git/config(prevents arbitrary code injection via Git hooks)..envand.env.*(prevents secret exfiltration or corruption).
This check applies across fs_write, fs_edit, and write inspection on shell_exec.
Governance of the subagent_merge Delta (3-way merge)
When an async job (spawn_subagent / /spawn) is merged with subagent_merge / /merge, the <root>..<merged_tree> delta is classified before anything touches disk:
Deny— Control Plane: if the delta touches.onyx/config.toml,.onyx/vault/**,.git/hooks/**,.git/config, or.env*, the entire merge is blocked (a single file blocks the whole delta; it is never applied partially).Ask— governance surfaces: if the delta touchessprout.tomlor.github/workflows/**, the merge approval must be explicit (never auto-approved), even if yourallowrules cover other tools.Safe: the rest of the delta follows the standard impact-based approval (Scent-Heated Approval).
The merge is 3-way via git merge-tree without moving the workspace's HEAD or index; the verdict is applied to the whole delta.
4. OS Sandbox, env_clear() & RAII ProcessJob
Every shell_exec call (and Sprout local process) runs on top of the shared onyx-workspace/src/sandbox.rs layer.
Sandbox Profiles (--sandbox)
| Mode | TUI Badge | Behavior |
|---|---|---|
workspace-write (default) | [SANDBOX:workspace] (Linux bwrap / macOS sandbox-exec), [SANDBOX:env+job] (Windows), or [SANDBOX:env+pgid] | env_clear(), OS write confinement (Linux/macOS), Win32 Job Objects / PGID, memory/PID limits, and offline network by default. On Windows, use strict-container for hard kernel FS/network isolation. |
strict-container | [SANDBOX:strict] | Executes commands inside an OCI container (docker, nerdctl, or podman) mounting the workspace. Ideal for unattended automation. |
off | [SANDBOX:off] | Disables OS sandbox wrapper (WorkspacePolicy, timeout, process cleanup, and Control Plane RO remain active). |
Network Policy (--sandbox-net)
| Policy | Behavior |
|---|---|
offline (default) | Blocks outbound network traffic and network commands pre-execution, and sets offline tool hints (CARGO_NET_OFFLINE, PIP_NO_INDEX, NPM_CONFIG_OFFLINE). |
localhost | Allows loopback traffic (127.0.0.1 / localhost) for testing local APIs or databases started by sprout.toml. |
unrestricted | No outbound network restriction (use only when downloading dependencies). |
Automatic Elevation Under --auto-approve
When --auto-approve is passed and config had mode = "off", openonyx automatically elevates the sandbox to workspace-write + offline unless you explicitly pass --sandbox off on the CLI.
Strict Environment Sanitization (env_clear())
Before spawning any child process:
- Calls
env_clear()and rebuilds a minimal safe allowlist (cleanPATH,HOME/USERPROFILE, standard toolchains). - Strips all secret-bearing variables (
*_API_KEY,*_TOKEN,AWS_*, etc.), ensuringshell_execcannot read yourGEMINI_API_KEYorOPENAI_API_KEY. - Redirects
TMP/TEMP/TMPDIRto a session-scoped temp directory. - Scrubs all captured output through
scrub_secretsbefore returning to the LLM or recording to transcripts.
Platform Drivers & RAII ProcessJob
- Windows (
win32-job): wraps commands in a Win32 Job Object withJOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSEplus memory/PID limits so timeouts or exitingopenonyxcleanly terminate the entire child tree. - Linux (
bwrap/landlock+PGID): uses Bubblewrap (bwrap) when available and passing a live runtime probe (bwrap_is_usable()). On hosts like Ubuntu 24.04 where AppArmor restricts unprivileged user namespaces,openonyxdetects it automatically and falls back safely while keepingenv_clear(), offline command blocking, Control Plane RO, and POSIXPGIDprocess-group cleanup. - macOS (
sandbox-exec+PGID): applies Seatbeltsandbox-execprofiles alongsideenv_clear()and POSIX process-group cleanup.
Inspect your host's detected sandbox driver and OCI runtime anytime with:
openonyx doctor
← 02. TUI & Daily Workflow · English Index · Next: 04. Time-Travel, Snapshots & Forking →
04. Time-Travel, Snapshots & Forking
A defining capability of openonyx is that the agent's entire state lives in a deterministic EAV graph that can be snapshotted, inspected, replayed offline, rolled back on disk, and forked without mutating the original timeline.
1. Session Vault (.onyx/vault/) & --auto-save
To keep your repository root free of stray .snaps_* folders, fork siblings, and .tr files, openonyx centralizes session storage inside <workspace>/.onyx/vault/:
<workspace>/.onyx/vault/
├── .gitignore # created automatically with `*`
├── 20261121-103500_qwen3-coder_main/ # created by --auto-save
│ ├── snapshots.onyxpack
│ └── 20261121-103500_qwen3-coder_main.tr
├── 20261121-103500_qwen3-coder_main.fork-t12/ # branch created by /fork or /rewind
├── feat-auth/ # --snapshot-dir feat-auth --record chat.tr
│ ├── snapshots.onyxpack
│ └── chat.tr
└── unassigned/ # standalone --record solo.tr (no snapshot-dir)
└── solo.tr
Routing Rules
--auto-save(orONYX_AUTO_SAVE=1): automatically creates<workspace>/.onyx/vault/<YYYYMMDD-HHMMSS>_<model>[_<branch|goal>]/storing bothsnapshots.onyxpackand<id>.trtogether, showsvault:<id>in the TUI header, and prints the exactopenonyx chat --resume <id>command on exit.- Short names (no
/or\separators):--snapshot-dir feat-auth→.onyx/vault/feat-auth/--snapshot-dir feat-auth --record chat.tr→ placeschat.trinside.onyx/vault/feat-auth/chat.tr.--record solo.tr(without--snapshot-dir) → places it in.onyx/vault/unassigned/solo.tr.
- Explicit paths preserved verbatim: any absolute path or path containing
/or\(./my-dir,C:\tmp\snaps,../other) is used as-is. - Transparent lookup on read:
--resume,inspect,rewind,replay, anddoctorcheck literal paths first and automatically resolve short names inside.onyx/vault/(and.onyx/vault/unassigned/for.trfiles). - Automatic Git & tool isolation:
openonyxwrites.onyx/vault/.gitignore(*) automatically sogit statusand/undoGit checkpoints never index vault files, whileWorkspacePolicyhides.onyx/vault/fromfs_list/glob_files/code_searchand protects it as read-only Control Plane.
2. How snapshots.onyxpack & Milestones Work
Whenever snapshot saving is enabled (--auto-save or --snapshot-dir <dir>), MilestoneSnapshotSystem captures snapshots only at meaningful transitions:
init— initial session state.spawn— root agent or subagent creation.approval:<tool>— pending mutating tool approval.tool:<tool>/tool_error:<tool>— tool observation or error.cmd:/agent,cmd:/undo,cmd:/rewind,cmd:/fork,cmd:/compact,cmd:/mode ...,cmd:/new— slash commands.settled,failed,exit— turn completion or clean exit.periodic— optional periodic frames when--snapshot-every <n>is passed.
All milestones are stored in a single append-only compressed container <dir>/snapshots.onyxpack (ONYXPK1 frames with zlib compression, canonical ONYXAG\x01\0 graph payloads, and 64-bit FNV-1a checksums):
- Crash tolerance: truncated trailing bytes from interrupted writes are safely ignored on read and healed automatically on the next append.
- Legacy compatibility: older directories containing
tick-*.binfiles remain readable via transparent fallback. - Optional retention: full history is kept by default so every tick stays rewindable; pass
--max-snapshots <n>for opt-in sliding-window retention (keepsinit+ latestn - 1milestones).
3. Inspecting Sessions (openonyx inspect)
Audit any session with zero API keys and zero disk mutations:
# List all milestones: tick, tag, compressed/raw size, FNV-1a checksum, and Git tree_sha
openonyx inspect feat-auth --list
# Machine-readable JSON output
openonyx inspect feat-auth --list --json
# Inspect the latest milestone or a specific tick
openonyx inspect feat-auth
openonyx inspect feat-auth --tick 24
openonyx inspect feat-auth --tick 24 --json
4. Step-by-Step Rollback (/undo)
Before every fs_write or fs_edit in BUILD mode, WorkspaceToolBridge captures a lightweight Git tree checkpoint using a temporary GIT_INDEX_FILE (git add -A + git write-tree):
- Never touches
HEADor your commits. - Never alters your staging index (
git add). - Works even in freshly initialized repositories with an unborn
HEAD.
Running /undo in openonyx chat:
- Marks the latest reversible effect as undone in the EAV graph (
ws.effect.undone). - Restores the exact pre-mutation
tree_shaon disk (restore_git_tree_checkpoint_for_targets). - Safe cleanup of newly created files: if the undone effect was an
fs_writethat created a new untracked file,/undodeletes it cleanly without touching unrelated untracked user files. - Invalidates session caches (
fs_readandscent_outline) so the agent sees the restored file contents.
5. Live In-Session Forking & Rewind (Inside the TUI)
When running chat with --auto-save, --snapshot-dir, or --resume, you can branch and rewind without leaving the TUI or overwriting the original timeline:
/fork [name] — Branch from Current Tick
/fork parser-experiment
# or omit name (creates <dir>.fork-t<tick>):
/fork
- Copies all milestones up to the current tick into a sibling directory inside
.onyx/vault/. - Switches the live
SharedPackStoreto the new branch and updates thevault:<session>badge in the header. - Leaves the original
snapshots.onyxpack100% untouched.
/rewind [tick] — Rewind Live Inside the TUI
# 1. List available milestones with ticks, tags, and Git checkpoints
/rewind
# 2. Rewind to tick 18 (or nearest prior milestone <= 18)
/rewind 18
- Active-work guard: if any agent is busy or an LLM request is in flight,
/rewindrefuses to run until settled. - Non-destructive by default: automatically forks into
<dir>.fork-t18, restores the graph to the target tick, reconciles orphaned disk effects (restoring Git tree + cleaning post-tickfs_writefiles), and prints a summary inMemory & Trace.
6. CLI Time-Travel & Forking
Resume from Latest Milestone
openonyx chat --resume feat-auth
Resume from a Historical Tick into a Safe Fork
# Creates .onyx/vault/feat-auth.fork-t12 and opens the TUI at tick 12 (original preserved)
openonyx chat --resume feat-auth --tick 12
# Specify a custom fork name inside .onyx/vault/
openonyx chat --resume feat-auth --tick 12 --fork-dir feat-auth-alt
# Equivalent via rewind --interactive / --tui
openonyx rewind feat-auth 12 --interactive
openonyx rewind feat-auth 12 --tui --fork-dir feat-auth-alt
Opt-In In-Place Truncation (--truncate-future)
To intentionally overwrite the original pack discarding ticks after <tick> instead of creating a sibling fork:
openonyx chat --resume feat-auth --tick 12 --truncate-future
Headless Rewind with --dry-run & Transcript Replay
# 1. Preview orphaned effects and Git rollback plan without touching disk
openonyx rewind feat-auth 12 --dry-run
# 2. Rewind and replay deterministically from a transcript (0 HTTP calls)
openonyx rewind feat-auth 12 --transcript chat.tr
7. Transcripts & 100% Offline Replay (ONYXTR2)
Recording with --auto-save or --record <file> writes all LLM decisions, structured tool calls (call_id), slash commands (Tab, /mode, /undo, /compact, etc.), and checkpoint markers ([checkpoint:<head>:<tree>]). The time debugger's 0-token primitives are sealed in the transcript as /__onyx_det_* (shell !cmd, /read, /inject, /step, /step-llm, and /graph surgery): replay reproduces them bit-for-bit with 0 I/O and 0 network (no command is re-executed).
# Record a session in the vault
openonyx chat --auto-save
# Replay offline later (0 network calls, 0 API key, 0 disk writes)
openonyx replay 20261121-103500_qwen3-coder_main.tr --snapshot-dir replay-check
8. Health Audit (openonyx doctor)
After a crash, network interruption, or before a delicate rewind, run:
openonyx doctor --snapshot-dir feat-auth --transcript chat.tr
doctor verifies:
- Git worktree health and any stray root
*.tr/snaps*artifacts. - Session vault status (
.onyx/vault/sessions,unassigned/transcripts, and.onyx/vault/.gitignore). snapshots.onyxpackintegrity (ONYXPK1header, FNV-1a checksums,ONYXAGgraph payloads, truncated-tail detection) and legacytick-*.binfiles.- Validity of Git
tree_shaobjects referenced in the side-effect ledger. - Transcript header and parse integrity (
ONYXTR1/ONYXTR2). - Host OS sandbox driver (
bwrap/sandbox-exec/win32-job) and OCI container CLI. sprout.tomlsyntax, acyclic DAG, container runtime, and occupied ports (if present).
9. Web Parity: the Time Debugger in openonyx serve
The embedded PWA has full parity with the TUI time debugger (SDD-07 Phase 4A): the same session state feeds both surfaces, so what you do from the browser affects the live session and vice versa.
- Tick pill: the header shows
#tick-pill(an accessible button). Live it readstick N; under freeze or with the cursor anchored in the past it reads⏸ X/Yand auto-opens the amber Time Debugger bar (you can close it; it reopens on the next freeze). - Amber bar: status (
⏸ TIME FROZEN · tick X / present Y/LIVE · tick Y), a slider that snaps to the nearest available tick (purged/future ticks are rejected with an actionable notice), ◀/▶ buttons,Freeze/Present,Step,Step 1 LLM, andResume— the last three go through the sealed command tunnel (/step 1,/step-llm,/go), not the scrub API: the branch is applied in the session with its gates. - Ephemeral API:
POST /api/v1/time/scrub(JSON:action: freeze|unfreeze|return_to_present|scrub_to|scrub_delta) mutates only the debugger's RAM state — 0 disk, 0 bus events — and replies with the updatedtime_debugsnapshot. It inherits the Bearer auth and CSRF guard of every/api/v1/*endpoint (401 without credentials, 403 cross-site, actionable 400 for future/purged ticks or unknown actions). - Plain prompts under freeze:
POST /api/v1/commandanswers409 Conflictwith an actionable message (Paused in TIME FROZEN: use /go to resume or /inject to stage memory…);/go,/graph …,/inject …,/read …,/step …,/step-llm,/timeand!cmdkeep working. - Memory surgery in the UI: with the root agent frozen, each root memory exposes
✎(edit via a dialog → flat/graph edit-mem <seq> <text>) and×(delete with confirmation →/graph drop-mem <seq>). - Projection preview & revert notice: the Web snapshot carries the full
time_debugblock (frozen,cursor_tick,present_tick,available_ticks,pending_revert_filesfrom the live graph's effects, 0 I/O) and, with--snapshot-dir+ a real LLM target, thebench_hint: a copy-pasteopenonyx bench --snapshot-dir … --tick … --models provider:modelcommand to compare the live model against a deterministic benchmark from the same cursor (SDD-05 §9.4 synergy).
Non-goal: Sprout and MCP server effects are external process side effects: TimeFreeze (TUI or Web) does not rewind them.
← 03. Modes, Permissions & OS Sandbox · English Index · Next: 05. Tools, Scent, Sprout & Skills →
05. Agent Tools, Scent, Sprout, Skills & Automation
This chapter catalogs all 24 tools exposed to the agent in openonyx (19 base + spawn_agent + 4 async subagent tools in isolated Git worktrees), explains multi-language AST navigation (onyx-scent 2.0), covers local service & container orchestration (sprout.toml), shows how to customize behavior with ONYX.md / skills, and outlines headless automation (openonyx run) and multi-model benchmarking (openonyx bench).
1. Complete 24-Tool Catalog
Read-Only & Coordination Tools (No Approval Required)
| Tool | Purpose | Key Notes |
|---|---|---|
fs_read | Read UTF-8 files (full or 1-based start_line/end_line range). | 64 KiB limit. Deduplicates unchanged reads (unchanged_since_tick) and overlapping/subset ranges (covered_by:start-end). Emits actionable errors if pointed at binary OnYX artifacts (ONYXTR1/2, ONYXPK1, ONYXAG). |
fs_list | List workspace directory tree up to max_depth (default 3). | Skips external symlinks, .git, target, node_modules, .onyx/vault/, *.tr, *.onyxpack. |
glob_files | Find workspace paths matching glob patterns (*, **, ?, [...], {a,b}). | Deterministic lexicographical order (or sort_by_mtime). Rejects path traversal. |
code_search | Literal or regex text search across the workspace. | Supports case_insensitive, include_glob, exclude_glob, and context_lines (0..=5) with scrub_secrets. |
scent_outline | Paginated @TOON v1 AST map of symbols, visibility, and line ranges. | Supports Rust, Python, Java, TypeScript (.ts/.tsx/.mts/.cts), JavaScript (.js/.jsx/.mjs/.cjs), Go, and C/C++ (.c/.h/.cc/.cpp/.cxx/.hh/.hpp); incremental blake3 cache + persistent binary .onyx/scent.idx cache + per-session seen_outlines dedup invalidated on edits/shell//undo; filters public_only, exclude_tests, cursor, max_rows (1..=500). |
scent_impact | Semantic call-impact graph (integer thermal diffusion 0..=10_000 bp, 1..=6 hops). | Reveals callers/dependents before refactoring shared symbols. |
scent_references | Resolves the exact AST definition of a symbol and its direct cross-references (callers, callees, implementors, type users) as @TOON v1 tuples. | target (symbol name, Type::method, or file::symbol); optional public_only, exclude_tests, pagination cursor/max_rows (1..=500). |
git_status | Read-only git status --short --branch. | Preferred over shell_exec for Git inspection. |
git_diff | Read-only git diff --no-color with optional path, staged, and context_lines. | Passes path strictly after --. |
load_skill | On-demand Markdown protocol/guide loader. | Searches .onyx/skills/, skills/, ~/.onyx/skills/, plus built-in scent and rust guides. |
plan_update | Updates structured checklist (pending, in_progress, completed). | Persisted to ws.plan.text and rendered in the right-hand Live Plan panel. |
service_status | Returns @TOON v1 status of all sprout.toml services. | Also projected into the Services (Sprout) side panel. |
service_logs | Reads recent lines from a Sprout service ring-buffer (up to 2,000 lines). | Lossy UTF-8 decoding + scrub_secrets filtering. |
spawn_agent | Delegates an independent subtask to a child subagent (WaitingChildren). | Default 32-step cap (overridable via max_steps JSON arg). With isolated: true the child works in its own isolated Git worktree (onyx/sub/agent-*) and the root is untouched until the 3-way is applied (section 1.1). |
Mutating Tools (Require Approval in BUILD; Blocked in PLAN/EXPLORE)
| Tool | Purpose | Key Notes |
|---|---|---|
fs_write | Create or overwrite a UTF-8 file. | Captures pre-mutation Git checkpoint, shows colorized diff preview, blocked on Control Plane RO. |
fs_edit | Unique exact replacement (old_text/new_text) or atomic multi-hunk edits: [...]. | Requires prior fs_read. Line-trimmed fallback & relative re-indentation applied in memory before write. Captures Git checkpoint. |
shell_exec | Run a shell command inside the workspace. | Configurable --shell-timeout (default 30s), env_clear(), OS sandbox, RAII ProcessJob, scrub_secrets, 32 KiB cap, invalidates fs_read/scent_outline caches. |
service_start | Start one service (id) or full DAG (all: true) from sprout.toml. | Honors depends_on topological order and waits on real probes (ready_port, ready_log, ready_cmd). |
service_stop | Stop one service (id) or all (all: true). | Clean teardown via stop_cmd / ProcessJob. |
service_exec | Run a command inside a running container (docker exec / nerdctl exec / podman exec). | Applies env_clear(), timeout, and scrub_secrets. |
Async Subagent Tools (Isolated Git Worktrees)
Besides spawn_agent (synchronous, same workspace), the agent can launch async jobs that run in isolated Git worktrees (onyx/sub/<job_id> branches) without blocking the root agent:
| Tool | Purpose | Key Notes |
|---|---|---|
spawn_subagent | Launch an async job in an isolated Git worktree. | goal required; max_steps default 32 (max 128); optional driver (native by default, or an [[external_drivers]] id — an external driver requires approval or allow spawn_subagent(<driver>), chapter 03). Parallelism capped by --max-subagents <n> (default 3, or ONYX_MAX_SUBAGENTS). |
subagent_status | Query async job status. | Optional job_id; shows status, branch, touched files, and summary. |
subagent_merge | 3-way merge the job's worktree into the root workspace (Scent-Heated Merge). | git merge-tree without moving HEAD or the index. The only one of the 4 with requires_approval: true. Delta governance: Deny on Control Plane (blocks the whole merge) and Ask on sprout.toml / .github/workflows/** (chapter 03); external drivers force Ask. |
subagent_discard | Cancel the job and remove its worktree and temp branch. | If the job is running, cancels the ProcessJob process tree. |
TUI slash equivalents: /spawn [--driver <id>] <goal> (launch), /subagents (list), /merge <job_id> (merge), and /discard <job_id> (discard). The full log of each job (job stdout/stderr, sealed through scrub_secrets) is stored in .onyx/vault/subagent-logs/<job_id>.log, and the F2 Agents view (chapter 02) lists the [bg] jobs with their status and → <driver> badge.
External drivers: with
driver = "opencode"(or any declared[[external_drivers]]), the job is delegated to an external CLI harness working in the same isolated worktree; process isolation, the Trust gate, and the network policy are documented in chapter 03 (section 2.7).
1.1. spawn_agent(isolated: true) — synchronous children in isolated worktrees
Beyond the async jobs above, spawn_agent accepts the isolated: true argument: the synchronous child (the parent goes WaitingChildren) works in its own isolated Git worktree, so parallel edits by several children never touch the root working tree until merged.
- Creation: when a pending
spawn_agent(isolated: true)is detected, the bridge lazily creates theonyx/sub/agent-<parent>-<child>-<seq>worktree viaWorktreeManager(SDD-09) withWorkspacePolicy::for_worktreeandNativeOfflinenetworking; creation uses acommit-treecheckpoint of the current working tree, without moving the rootHEADor index. If the workspace is not a Git repo (or Git < 2.38), the parent receives a sticky, actionable error (root untouched). - Finalization: when the child terminates (
Done/Failed) or vanishes from the graph, the bridge finalizes it unconditionally: it captures the ephemeral commit of the child's final working tree, evaluates the 3-way (git merge-tree, root intact), and records anIsolatedWorktreeResult(Pending/Applied/Discarded/Transferred). - Resolution: with a clean 3-way the result is applied to the root (or discarded) sequentially; with conflicts, the worktree is transferred to
SubagentManagerand the work flows through the normalsubagent_status/subagent_merge/subagent_discardpath (same approval and governance asspawn_subagentjobs). Result notifications follow the async-job semantics (last_completed_proposalsand, withproactive_notifications, anIngressEvent::Command). - Cleanup: the worktree is removed on apply/discard, on the bridge
Drop, and by the orphaned-worktree pruning inopenonyx doctor; the temp branchonyx/sub/<job_id>is always deleted.
Dynamic MCP Tools (mcp__<server>__<tool>)
On top of the fixed catalog above, every MCP server declared in [mcp.servers.<name>] (chapter 03, section 2.8) injects its tools dynamically into the LLM under the name mcp__<server>__<tool>:
- Discovery at startup: the
initialize→tools/listhandshake (paginated, max 16 pages) retrieves each tool's name, description, andinputSchema; schemas are normalized before being declared to the provider (Gemini, OpenAI, and Anthropic). - Always approval-gated:
requires_approval = trueon everymcp__*tool: they ask for interactive approval inBUILD(unless a more specificallowrule) and areDenyinPLAN/EXPLORE, exactly like mutations. - Isolation & sanitization: a dead server never aborts the session, and results pass through
truncate_utf8+scrub_secrets. - 0-I/O replay: under
openonyx replaythemcp__*tools are reconstructed from the transcript itself, without contacting any server.
Subagents do not receive
mcp__*tools: only the session's root agent sees the MCP registry (worktree jobs do not inherit it).
2. Semantic AST Navigation with onyx-scent (Scent 2.0)
Instead of burning tokens reading entire multi-thousand-line files, openonyx encourages a two-step workflow:
scent_outline: fetches function, struct, trait, class, method, type alias and component signatures, visibility, and exact line ranges in compact@TOON v1format (paginated viacursor/next_cursor). Repeated calls on unchanged files hit the per-sessionseen_outlinescache, which invalidates automatically afterfs_edit,fs_write,shell_exec, or/undo.scent_impact/scent_references+fs_read(start_line, end_line): checks the blast radius (or resolves a symbol's exact definition and direct cross-references) before editing public symbols, then reads only the exact lines required.
Languages supported by
onyx-scent(Scent 2.0): 7 languages — Rust (.rs), Python (.py), Java (.java), TypeScript (.ts,.tsx,.mts,.cts), JavaScript (.js,.jsx,.mjs,.cjs), Go (.go), and C/C++ (.c,.h,.cc,.cpp,.cxx,.hh,.hpp). In JS/TS it also extracts type aliases (EntityKind::TypeAlias) and components (EntityKind::Component: PascalCase functions with JSX in.tsx/.jsx), andis_callableincludes both. For other languages, the agent usesglob_files+code_searchv2 +fs_read.
Incremental binary cache .onyx/scent.idx
ONYXSCI1: the workspace AST index is persisted to.onyx/scent.idx(machineryONYXSCI1: magic + version + entries sorted byrel_path+ finalblake3checksum) alongside a hygiene.onyx/.gitignorethat ignoresscent.idxandscent.idx.tmp*; any anomaly (truncated file, wrong magic/version, invalid checksum) is silently ignored and the index is rebuilt clean.- Incremental reload: each refresh only re-parses files whose mtime/content changed (hash-verified), so repos with thousands of files update in tens of milliseconds; the file is written atomically (temp file + rename).
- Excluded from Git artifacts: subagent ephemeral checkpoints (
commit-tree) and worktree impact evaluation exclude.onyx/scent.idx*and its.gitignore, so a child's work is never polluted by OnYX's own operational artifacts. scentCLI: theonyx-scentcrate (clifeature) exposes thescentbinary withoutline,impact, andreferencessubcommands (same@TOON v1output as the agent tools, for direct use in scripts/CI).
3. Local Process & Container Orchestration (sprout.toml)
If your project relies on local services (Docker/Rancher databases, backend APIs, workers, dev servers), add a sprout.toml at the workspace root.
onyx-workspace runs a pure-std supervisor (0 tokio) that validates the dependency DAG (rejecting cycles), starts services in topological order, checks real readiness probes, and tears down all child trees cleanly on exit via RAII ProcessJob.
Modern Format ([runtime] + [services.<id>])
[runtime]
# Optional: "docker" | "nerdctl" | "podman" (auto-detected if omitted)
container_cli = "docker"
[services.db]
name = "Local Postgres"
kind = "container"
cmd = "docker compose up -d postgres"
stop_cmd = "docker compose stop postgres"
logs_cmd = "docker compose logs --tail=100 postgres"
container = "myapp-postgres"
# Optional: run `service_exec` as a specific user (e.g. "1000:1000" or "app")
# exec_user = "1000:1000"
ready_port = 5432
[services.api]
name = "Backend API"
kind = "process"
cwd = "backend"
cmd = "cargo run --bin api"
depends_on = ["db"]
ready_port = 8080
ready_log = "Listening on 127.0.0.1:8080"
The legacy Sprout format ([global] + [[service]] with env_wrapper, dir, debug_port, depends_on, optional, enabled) is also supported.
Interactive TUI Control
/services: prints the@TOON v1service status table intoMemory & Trace./service start <id|all>: starts a service (plus dependencies) or the entire stack./service stop <id|all>: stops a service or all services./service logs <id> [tail]: prints recent lines from the service log buffer.- On terminals
>= 100columns wide, statuses appear live in the right-handServices (Sprout)panel, andopenonyx doctorauditssprout.tomlsyntax, DAG cycles, container runtime availability, and occupied ports.
Sandbox network, trust & container note: if the agent needs
shell_execto hit a local Sprout endpoint (e.g.http://127.0.0.1:8080/health), launch with--sandbox-net localhost(or setnetwork = "localhost"in.onyx/config.toml). In addition, when a workspace is not yet trusted (openonyx trust addor/trust), Sprout displays[UNTRUSTED — run /trust]and blocksstart,stop, andexecuntil the currentsprout.tomlhash is approved (any 1-byte edit revokes trust automatically).container_clistrictly acceptsdocker,nerdctl, orpodman, and optionalexec_userrunsservice_execas the specified user.
4. Project Instructions (ONYX.md / AGENTS.md)
On startup (chat, run, and live rewind), openonyx automatically loads Markdown rules in order (up to 16 KiB total, filtered through scrub_secrets):
~/.onyx/AGENTS.mdand~/.onyx/ONYX.md(personal global rules)<workspace>/AGENTS.mdand<workspace>/ONYX.md(project rules)
It also injects a host OS shell hint (Windows PowerShell vs Unix/POSIX) so the model emits valid commands for your machine.
Example <workspace>/ONYX.md:
# Project Conventions
- Always run `cargo test --workspace` after editing Rust code.
- Never edit generated files under `dist/`.
- Keep public API errors concise and actionable.
5. Authoring Custom Skills (SKILL.md)
Rather than bloating ONYX.md on every turn, package domain checklists as on-demand skills. At startup openonyx injects only a compact summary (discover_skills_summary), and the agent loads the full text via load_skill("<name>") only when relevant.
Skill Discovery Priority
<workspace>/.onyx/skills/<name>/SKILL.md(recommended per-project location) or<name>.md<workspace>/skills/<name>/SKILL.mdor<name>.md~/.onyx/skills/<name>/SKILL.mdor<name>.md(global user skills)- Built-in skills:
scentandrust
Example Custom Skill (.onyx/skills/deploy-checks/SKILL.md)
---
name: deploy-checks
description: Pre-deploy verification checklist and safe SQL migration guidelines.
---
# Pre-Deploy Verification
1. Check `git_diff` for destructive migrations lacking a rollback path.
2. Verify `cargo clippy --workspace --all-targets -- -D warnings` passes cleanly.
3. Confirm no staging tokens or internal URLs remain in config files.
Best practices:
- Include
name:anddescription:within the first 20 lines. - Never include real secrets (all content is filtered through
scrub_secrets). - Keep files well below
64 KiB.
6. Headless Automation & CI (openonyx run)
Run a single goal non-interactively with full vault recording:
# Read-only security/code audit
openonyx run "review git_diff and list potential security regressions" \
--effort medium \
--max-steps 32 \
--auto-save
# Scoped automated fix with offline sandbox
openonyx run "fix clippy warnings and verify with cargo test" \
--auto-approve \
--sandbox workspace-write \
--sandbox-net offline \
--shell-timeout 120 \
--auto-save
Even with --auto-approve, [permissions].deny rules in .onyx/config.toml and Control Plane RO protection remain enforced.
← 04. Time-Travel, Snapshots & Forking · English Index · Next: 06. CLI Reference & Troubleshooting →
06. Complete CLI Reference & Troubleshooting
Quick reference for all CLI subcommands, flags, environment variables, HTTP/SSE resilience, and solutions to common real-world issues on Windows, Linux, and macOS.
1. Subcommand Overview
openonyx chat [OPTIONS] [--resume <dir> [--tick <n>] [--fork-dir <dir>] [--truncate-future]]
openonyx run <goal> [OPTIONS]
openonyx replay <transcript> [--workspace <dir>] [--snapshot-dir <dir>] [--snapshot-every <n>] [--max-snapshots <n>]
openonyx inspect <snapshot_dir> [--tick <n>] [--list] [--json]
openonyx rewind <snapshot_dir> <tick> [--transcript <file>] [--interactive | --tui] [--fork-dir <dir>] [--truncate-future] [--dry-run] [OPTIONS]
openonyx bench --snapshot-dir <dir> --tick <n> --models <list> [--goal <text>] [--verify <cmd>] [--out <file.json>] [--max-steps <n>] [OPTIONS]
openonyx doctor [--workspace <dir>] [--snapshot-dir <dir>] [--transcript <file>]
openonyx trust [--workspace <dir>] [add | list | check | revoke] [--list | --check | --revoke]
openonyx serve [--workspace <dir>] [--bind <ip:port>] [--api-key <key>] [--cors-origin <origin>] [OPTIONS]
openonyx [--help | -h | --version | -V]
2. Complete Flag Table
| Flag | Applies To | Description / Default |
|---|---|---|
-w, --workspace <dir> | All | Target workspace directory (default: current working directory). |
--provider <gemini|openai|anthropic> | chat, run, rewind | LLM backend (gemini default; openai for OpenAI/OpenRouter/Ollama/vLLM/LM Studio; anthropic for the native Messages API). |
--model <name> | chat, run, rewind | Model name (defaults: gemini-4-hydrogen on Gemini, gpt-4o on OpenAI, claude-sonnet-4-5 on Anthropic). |
--effort <low|medium|high> | chat, run, rewind | Reasoning/thinking effort (thinkingLevel / reasoning_effort; on anthropic it maps to a thinking budget of 2048/8192/16384 unless an explicit budget is set). |
--thinking-budget <n> | chat, run, rewind | Anthropic extended-thinking budget in tokens (0 = off, or 1024..=60000; or ANTHROPIC_THINKING_BUDGET). Raises max_tokens above the budget. |
--api-base <url> | chat, run, rewind | Custom API base URL (http:// allowed only on loopback localhost/127.0.0.1/[::1]; remote hosts require https://). |
--allow-custom-auth-host | chat, run, rewind | Explicit opt-in to send API keys to non-official remote HTTPS endpoints (or ONYX_ALLOW_CUSTOM_AUTH_HOST=1). |
--trust-workspace | chat, run, rewind, serve | Trust the current workspace in memory for this run (without writing ~/.onyx/trusted_workspaces.toml). |
--bind <ip:port> | serve | HTTP/SSE bind address (default: 127.0.0.1:8787; non-loopback requires explicit --api-key >= 16 chars). |
--api-key <key> | serve | API key for authentication (HttpOnly cookie or Authorization: Bearer; randomly generated on loopback if omitted). |
--cors-origin <url> | serve | Explicit allowed browser origin for external SPAs (e.g. Svelte dev server http://localhost:5173; never *). |
--sandbox <off|workspace-write|strict-container> | chat, run, rewind | OS sandbox profile for shell_exec (default: workspace-write). |
--sandbox-net <offline|localhost|unrestricted> | chat, run, rewind | Sandbox network policy (default: offline). |
--auto-approve | chat, run, rewind | Skip interactive approvals for mutating tools (deny rules still apply; sandbox elevates off → workspace-write + offline unless --sandbox off). |
--ignore-deny | chat, run, rewind | Explicitly bypass [permissions].deny rules from .onyx/config.toml. |
--max-steps <n> | chat, run | Max root agent steps per turn (default: 128 in chat, 64 in run; subagents capped at 32 by default). |
--max-subagents <n> | chat, run, serve, rewind --interactive | Max parallel async subagent Git worktrees (default: 3, or ONYX_MAX_SUBAGENTS). |
--shell-timeout <secs> | chat, run | Timeout in seconds per shell_exec command (default: 30s). |
--auto-save | chat, run | Auto-create .onyx/vault/<YYYYMMDD-HHMMSS>_<model>[_<branch|goal>]/ storing both snapshots.onyxpack and <id>.tr together (or ONYX_AUTO_SAVE=1). |
--record <f>, --save-transcript <f> | chat, run | Save deterministic ONYXTR2 transcript (short names go inside --snapshot-dir, or .onyx/vault/unassigned/ if no snapshot dir). |
--snapshot-dir <dir> | chat, run, replay, doctor | Snapshot directory for snapshots.onyxpack (short names resolve under .onyx/vault/<dir>/). |
--snapshot-every <n> | chat, run, replay | Also capture periodic periodic milestones every <n> ticks. |
--max-snapshots <n> | chat, run, replay | Opt-in sliding-window retention (keeps init + latest n - 1 milestones). |
-r, --resume <dir> | chat | Resume from latest milestone (or --tick <n>) in <dir> (resolves short names in .onyx/vault/). |
--tick <n> | inspect, chat --resume | Specific tick to inspect or resume/fork from. |
--fork-dir <dir> | chat --resume --tick, rewind --interactive | Destination directory for forked snapshots (short names resolve under .onyx/vault/). |
--truncate-future | chat --resume --tick, rewind | Opt-in destructive truncation: overwrite source pack in place instead of creating a sibling fork. |
--interactive, --tui | rewind | Open interactive TUI at the restored tick instead of running headless. |
-l, --list | inspect | List all stored milestones with tags, sizes, FNV-1a checksums, and Git checkpoints. |
--json | inspect | Emit machine-readable JSON output. |
--transcript <file> | rewind, doctor | Replay transcript from rewind tick (rewind) or validate transcript (doctor). |
--dry-run | rewind | Preview orphaned effects and Git rollback plan without modifying disk. |
--models <list> | bench | Comma-separated candidate list: <provider>:<model> (live LLM, e.g. gemini:gemini-2.5-pro,openai:gpt-4o) and/or replay:<label>=<file.tr> / replay:<file.tr> (offline ONYXTR2 transcript, deterministic). |
--verify <cmd> | bench | Verification command executed sandboxed inside the candidate's worktree after it settles (same pipeline as shell_exec); its exit 0 decides passed_verify. Without --verify, passed_verify = agent finished Done and the session settled. |
--out <file.json> | bench | Write the full pretty-printed JSON report (metadata + results). |
--goal <text> | bench | Root agent goal when no agent is active at --tick (required in that case). |
-h, --help / -V, --version | Global | Print help or version and exit 0. |
openonyx bench — full reference
Multi-model benchmark from an identical snapshot: every candidate runs in a throwaway worktree (bench-<pid>-<idx>-<label>) rewound to --tick (reconcile_rewind_effects_report), with a fresh session host (request_restore + 1 step); afterwards the root and HEAD remain 100 % intact and the worktree is removed (RAII guard; also on error or panic).
# Live + offline replay comparison, with verification and a JSON report
openonyx bench \
--snapshot-dir .onyx/vault/20261125-100000_gpt-4o \
--tick 12 \
--models "gemini:gemini-2.5-pro,openai:gpt-4o,replay:baseline=run_baseline.tr" \
--goal "fix the failing test in src/app.rs" \
--verify "cargo test --workspace" \
--out bench_report.json \
--auto-approve \
--sandbox workspace-write \
--sandbox-net offline
- Candidates (
--models):<provider>:<model>withprovider ∈ gemini|openai|anthropic(credentials via the usualGEMINI_API_KEY/OPENAI_API_KEY/ANTHROPIC_API_KEYvariables or--api-base);replay:<label>=<path.tr>sets the label explicitly;replay:<path.tr>uses the file stem as the label. Parsing splits on:first, then=, so Windows drive-letter paths (replay:C:\runs\a.tr) survive intact. - Per candidate (sequential): rewind the worktree to the tick → fresh restored host → if no agent is active at the tick, spawn a root agent from
--goal→ run until settled (internal 256-tick cap) with real telemetry (tokens/cost) for live candidates (replay: tokens/cost0). --auto-approve: for unattended runs on disposable worktrees: each candidate runs only inside its own worktree and the root is never touched;[permissions].denystill applies.- Output: a 9-column Markdown table on
stdout—| model | passed_verify | ticks | tool_calls | input_tokens | cached_tokens | output_tokens | estimated_cost_usd | wall_time_ms |— plus, with--out, the JSON report (metadatawith snapshot/tick/models/verify + per-candidateresultswith every column). - Reused flags:
--workspace <dir>,--sandbox <off|workspace-write|strict-container>,--sandbox-net <offline|localhost|unrestricted>,--shell-timeout <secs>,--trust-workspace,--api-base <url>,--allow-custom-auth-host,--effort <low|medium|high>,--thinking-budget <n>(a live candidate determines its ownprovider:model). - Actionable validation: missing
--snapshot-dir/--tick/--modelsproduces an error naming the missing flag; unknown provider →unsupported provider ... (expectedgemini,openaioranthropic); a missing snapshot store → floor warning, not an error.
3. Environment Variables
| Variable | Provider | Description |
|---|---|---|
ONYX_PROVIDER | All | Default provider (gemini | openai | anthropic). |
GEMINI_API_KEY | Gemini | Google AI Studio API key (fallback: ONYX_API_KEY). |
OPENAI_API_KEY | OpenAI | API key for --provider openai (fallback: ONYX_API_KEY; optional with local --api-base). |
ANTHROPIC_API_KEY | Anthropic | API key for --provider anthropic (fallback: ONYX_API_KEY). |
ONYX_API_KEY | All | Shared fallback key if provider-specific key is unset. |
ONYX_MODEL | All | Default model override (fallbacks: ONYX_GEMINI_MODEL, OPENAI_MODEL, ANTHROPIC_MODEL). |
ONYX_EFFORT | All | Default reasoning effort (low | medium | high; fallbacks: GEMINI_THINKING_LEVEL, OPENAI_REASONING_EFFORT; on Anthropic, ANTHROPIC_THINKING_BUDGET governs thinking). |
ONYX_AUTO_SAVE | Both | Enable --auto-save by default (1 | true | yes | on) storing sessions in .onyx/vault/. |
ONYX_MAX_SUBAGENTS | Both | Max parallel async subagent worktrees (used when --max-subagents <n> is omitted; default: 3). |
GEMINI_API_BASE | Gemini | Custom Gemini API base URL. |
OPENAI_API_BASE / OPENAI_BASE_URL | OpenAI | Custom OpenAI-compatible API endpoint (default: https://api.openai.com/v1). |
ANTHROPIC_API_BASE | Anthropic | Custom Anthropic API base URL (default: https://api.anthropic.com). |
ANTHROPIC_THINKING_BUDGET | Anthropic | Extended-thinking budget in tokens (0 = off, or 1024..=60000); takes precedence over the --effort-derived budget. |
LLM, driver & MCP config in
config.toml: beyond flags and environment variables,.onyx/config.tomlaccepts[[llm_profiles]](chapter 03, section 2.6),[[external_drivers]](chapter 03, section 2.7), and[mcp.servers.<name>](chapter 03, section 2.8) blocks. A profile's key resolves in the orderapi_key_env→ the provider's standard variable →ONYX_API_KEY.
4. HTTP/SSE Resilience on OpenAI, vLLM & Corporate Proxies
Local inference servers and proxies (vLLM, LiteLLM, nginx, Cloudflare) occasionally close chunked SSE streams abruptly right after emitting finish_reason or return transient errors (408, 429, 500, 502, 503, 504, or brief transport drops).
open-onyx/src/openai.rs builds in two automatic safeguards:
- Completed-SSE EOF tolerance: if a chunk decode error happens after
finish_reason/[DONE]with complete assistant content ortool_calls, the response is accepted cleanly instead of failing the turn. - Automatic transient retries with backoff: retries transient transport/408/429/5xx/stream errors up to 2 times (
400ms,1200ms) before surfacing an error to the agent.
The native open-onyx/src/anthropic.rs adapter applies the same retry policy (408, 429, 500, 502, 503, 504, and Anthropic's own overloaded_error 529), honoring the retry-after header when the server sends it.
5. Common Troubleshooting
1. GEMINI_API_KEY environment variable is not set
- For Gemini: set
GEMINI_API_KEY(PowerShell:$env:GEMINI_API_KEY="..."; bash/zsh:export GEMINI_API_KEY="..."). - For Ollama / vLLM / LM Studio: pass
--provider openai --api-base http://localhost:11434/v1 --model <model>(no API key needed). - For
inspect,replay,rewind --dry-run, anddoctor: no API key is ever required.
2. Agent attempts to read a .tr, .onyxpack, or tick-*.bin file with fs_read
fs_read detects binary OnYX headers (ONYXTR1, ONYXTR2, ONYXPK1, ONYXAG) and returns an actionable error pointing the agent to openonyx inspect / openonyx replay.
3. shell_exec fails with an offline/network error during cargo build or curl
The default sandbox policy is --sandbox-net offline (also injecting CARGO_NET_OFFLINE=true):
- To reach local Sprout services (
127.0.0.1): pass--sandbox-net localhost. - To fetch crates or internet resources: pass
--sandbox-net unrestricted.
4. Ubuntu 24.04+: bwrap cannot create unprivileged user namespaces (AppArmor)
Ubuntu 24.04 restricts unprivileged user namespaces via AppArmor. openonyx probes bwrap_is_usable() at runtime and automatically falls back cleanly so shell_exec keeps working. Verify your host driver with openonyx doctor.
5. Ctrl+Tab does not switch agents in my terminal
Some terminal emulators (Windows Terminal, tmux, SSH) swallow Ctrl+Tab. Use the F2 key (which now opens the Agents view, chapter 02) or /agent [id|name], which work across all terminals.
6. /rewind refuses to run while an agent is busy
Live /rewind <tick> requires no active agents (thinking, acting, waiting_children) and no in-flight LLM calls. Wait for Settled, or quit with Esc and run openonyx chat --resume <session> --tick <n>.
7. Windows PowerShell quoting or bash-isms in shell_exec
openonyx tells the model the host OS (Windows PowerShell vs Unix/POSIX), and you can reinforce in <workspace>/ONYX.md to prefer native tools (code_search, glob_files, fs_read, git_diff) over shell commands.
8. Unexpected crash during a long session
- Run
openonyx doctor --snapshot-dir <session>to check for any truncated tail bytes insnapshots.onyxpack. - Inspect intact milestones with
openonyx inspect <session> --list. - Resume with
openonyx chat --resume <session>— truncated tail bytes are safely ignored on read and healed automatically on the next append.
9. openonyx doctor warns or errors on an external driver ([[external_drivers]])
doctor audits the [[external_drivers]] declarations (chapter 03, section 2.7):
- Built-in
opencodepreset:[WARN]when theopencodebinary is not onPATH(the preset is skipped). - Declared driver whose
binis missing:[ERR]—/spawn --driver <id> will fail at runtime. binfound but the--versionprobe (3 s deadline, sanitized environment) times out:[ERR]; if it errors out instead (e.g., wrong flags):[WARN].prompt_transport = "arg"on Windows:[WARN]when the binary resolves to a.cmd/.batwrapper (rejected at spawn time).network_allowlistwithout--sandbox strict-container:[WARN]— the allowlist is advisory outsidestrict-container; a declared driver withoutnetwork_allowlistisLocalhostOnlyunless the sandbox relaxes it.
10. An MCP server does not connect, or [mcp.servers.*] is ignored
openonyx doctor audits the servers declared in [mcp.servers.<name>] (chapter 03, section 2.8) with a 5 s-capped handshake (a dead server can never hang doctor):
ConnectedorDisabled: informational[CHECK].Failed(...)(missing binary, handshake timeout, server error): actionable[ERR]with an already-scrubbed message; the session keeps running without that server (failure isolation).- Untrusted workspace with project
[mcp.servers.*]:[WARN]MCP config in ... ignored: workspace is not trusted (use --trust-workspace or openonyx trust)— approve withopenonyx trustor use--trust-workspace. mcp__*tools always ask for approval inBUILDand areDenyinPLAN/EXPLORE; to auto-approve them, declareallow = ["mcp__<server>__*"]in.onyx/config.toml(trusted workspace).
11. The Web (or the TUI) rejects my prompt: 409 Conflict / "Paused in TIME FROZEN"
That is the TimeFreeze guard (chapter 04, section 9): the session is frozen (an active time breakpoint) and an out-of-order plain prompt would break the bit-for-bit replay. It is not a bug — these are the escape routes:
/go(or/unfreeze): branches if the cursor looks at the past, then resumes at present./inject <text>//graph …//read …//step [n]//step-llm/! <cmd>: keep working under freeze (sealed 0-token primitives).- In the Web, the amber bar (press
#tick-pill) has aResumebutton; in the TUI,Escreturns to present without quitting andCtrl+Ttoggles the freeze. - On
POST /api/v1/commandthe 409 carries the full actionable message; a400onPOST /api/v1/time/scrubmeans a future/purged tick or an unknown action (the body explains it).